简体   繁体   English

使用jq从多个输入对象生成单个JSON数组

[英]Generate single JSON array from several input objects using jq

I do have several similar JSON objects (eg in files): 我确实有几个类似的JSON对象(例如,在文件中):

file_1.json: {"myArray":[{a},{b}]}
...
file_n.json: {"myArray":[{n},{m}]}

I would like to transform all these files into one output with the following format, using jq and Linux or Windows command line tools: 我想使用jq和Linux或Windows命令行工具将所有这些文件转换为以下格式的输出:

result_file.json: [{a},{b},...,{n},{m}]

So, I just want one array having all the objects that can be found in the "myArray" arrays from the different inputs. 因此,我只想要一个具有所有对象的数组,这些对象可以在“ myArray”数组中从不同的输入中找到。

Currently I use this command, which separates the objects, but doesn't create an array that includes them: 当前,我使用此命令来分隔对象,但不创建包含它们的数组:

type file_1.json file_n.json | jq ".result[]" > result_file.json

(replace type with cat on Linux) (在Linux上用cat替换类型)

How can I get the format right? 如何获得正确的格式?

You can "slurp" your inputs: 您可以“输入”您的输入:

-s read (slurp) all inputs into an array; -s将所有输入读取(吸取)到数组中; apply filter to it; 对它应用过滤器;

(man jq) (男人jq)

Like that: 像那样:

1.json 1.json

{"myArray":[1,2,3]}

2.json 2.json

{"myArray":[3,4,5]}

%jq -s '[.[].myArray[]]' 1.json 2.json

[
  1,
  2,
  3,
  3,
  4,
  5
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM