【问题标题】:jq: output array of json objects [duplicate]jq:json对象的输出数组[重复]
【发布时间】:2016-10-29 21:41:12
【问题描述】:

假设我有输入:

{
    "name": "John",
    "email": "john@company.com"
}
{
    "name": "Brad",
    "email": "brad@company.com"
}

如何获得输出:

[
    {
        "name": "John",
        "email": "john@company.com"
    },
    {
        "name": "Brad",
        "email": "brad@company.com"
    }
]

我都试过了:

jq '[. | {name, email}]'

jq '. | [{name, email}]'

这两个都给了我输出

[
    {
        "name": "John",
        "email": "john@company.com"
    }
]
[
    {
        "name": "Brad",
        "email": "brad@company.com"
    }
]

我在文档中也没有看到数组输出的选项,感谢任何帮助

【问题讨论】:

  • 如何为新数组命名而不是匿名数组?所以 { "people": [ { "name": "Brad", "email": "brad@company.com" } ]}
  • @user372429 你只需将 {people: } 包裹在你的输出中,所以它应该看起来像: jq -s '{people: . }'
  • 试试jq [.[] | {name,email}]

标签: bash jq


【解决方案1】:

使用 slurp 模式:

  o   --slurp/-s:

      Instead of running the filter for each JSON object
      in the input, read the entire input stream into a large
      array and run the filter just once.
$ jq -s '.' < tmp.json
[
  {
    "name": "John",
    "email": "john@company.com"
  },
  {
    "name": "Brad",
    "email": "brad@company.com"
  }
]

【讨论】:

  • 如果需要,您还可以将初始 jq 结果通过管道传输到jq -s。即... | jq '.foo[].bar' | jq -s
  • 我喜欢添加另一个管道以减少每个命令中的步骤,但不要忘记 '.' ... | jq '.foo[].bar' | jq -s '.'
  • @Adam jq 如果其标准输出是终端,则假定 . 的过滤器。
  • 您可以将过滤器包裹在[...] 中,而不是再次运行jq... | jq '[.foo[].bar]'.
  • @chepner,我正在输入更多命令,所以默认设置对我没有影响。抱歉,我以为你错过了最后一部分。
猜你喜欢
  • 1970-01-01
  • 2019-07-09
  • 1970-01-01
  • 2020-06-20
  • 2021-08-20
  • 2020-03-28
  • 2019-10-25
  • 2021-10-20
  • 2017-05-19
相关资源
最近更新 更多