Use jq to concatenate JSON arrays in multiple files

Gre*_*ard 1 json jq

I have a series of JSON files containing an array of records, e.g.

$ cat f1.json
{
  "records": [
    {"a": 1},
    {"a": 3}
  ]
}

$ cat f2.json
{
  "records": [
    {"a": 2}
  ]
}
Run Code Online (Sandbox Code Playgroud)

I want to 1) extract a single field from each record and 2) output a single array containing all the field values from all input files.

The first part is easy:

jq '.records | map(.a)' f?.json
[
  1,
  3
]
[
  2
]
Run Code Online (Sandbox Code Playgroud)

But I cannot figure out how to get jq to concatenate those output arrays into a single array!

我没有结婚jq;如有必要,我会很乐意使用其他工具。但我很想知道如何与这样做jq,因为这是我一直在试图找出了多年

oli*_*liv 11

使用-s(或--slurp):

jq -s 'map(.records[].a)' f?.json
Run Code Online (Sandbox Code Playgroud)


pea*_*eak 6

假设您的 jq 具有inputs(这适用于 jq 1.5 及更高版本),使用它会最有效,例如:

jq -n '[inputs.records[].a]' f*.json
Run Code Online (Sandbox Code Playgroud)


Ini*_*ian 5

如果您的输入文件很大,则读取文件可能会占用大量内存,在这种情况下您可以以迭代方式工作,一次reduce将数组的内容附加到一个对象.a

jq -n 'reduce inputs.records[].a as $d (.; . += [$d])' f?.json
Run Code Online (Sandbox Code Playgroud)

-n标志是为了确保使用 中可用的数据从头开始构建输出 JSON inputs。由于空输入,该reduce函数采用的初始值为。然后,对于每个输入对象,确保数组内容附加在一起。.null. += [$d].a