bash jq:json 对象的输出数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38061346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:20:37  来源:igfitidea点击:

jq: output array of json objects

bashjq

提问by Mauricio Trajano

Say I have the input:

说我有输入:

{
    "name": "John",
    "email": "[email protected]"
}
{
    "name": "Brad",
    "email": "[email protected]"
}

How do I get the output:

我如何获得输出:

[
    {
        "name": "John",
        "email": "[email protected]"
    },
    {
        "name": "Brad",
        "email": "[email protected]"
    }
]

I tried both:

我都试过:

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

and

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

which both gave me the output

两者都给了我输出

[
    {
        "name": "John",
        "email": "[email protected]"
    }
]
[
    {
        "name": "Brad",
        "email": "[email protected]"
    }
]

I also saw no options for an array output in the documentations, any help appreciated

我在文档中也没有看到数组输出的选项,任何帮助表示赞赏

回答by chepner

Use slurp mode:

使用 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.
  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": "[email protected]"
  },
  {
    "name": "Brad",
    "email": "[email protected]"
  }
]