Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jq to concatenate JSON arrays in multiple files

Tags:

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}
  ]
}

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
]

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

I'm not married to jq; I'll happily use another tool if necessary. But I would love to know how to do this with jq, because it's something I have been trying to figure out for years.

like image 963
Greg Ward Avatar asked Dec 02 '25 06:12

Greg Ward


2 Answers

Use -s (or --slurp):

jq -s 'map(.records[].a)' f?.json
like image 167
oliv Avatar answered Dec 03 '25 20:12

oliv


Assuming your jq has inputs (which is true of jq 1.5 and later), it would be most efficient to use it, e.g. along the lines of:

jq -n '[inputs.records[].a]' f*.json
like image 32
peak Avatar answered Dec 03 '25 20:12

peak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!