How to combine the sequence of objects in jq into one object?

ArraysJsonAdditionJqFileslurp

Arrays Problem Overview


I would like to convert the stream of objects:

{
  "a": "green",
  "b": "white"
}
{
  "a": "red",
  "c": "purple"
}

into one object:

{
  "a": "red",
  "b": "white",
  "c": "purple"
}

Also, how can I wrap the same sequence into an array?

[    {      "a": "green",      "b": "white"    },    {      "a": "red",      "c": "purple"    }]

Sadly, the manual is seriously lacking in comprehensiveness, and googling doesn't find the answers either.

Arrays Solutions


Solution 1 - Arrays

If your input is a stream of objects, then unless your jq has inputs, the objects must be "slurped", e.g. using the -s command-line option, in order to combine them.

Thus one way to combine objects in the input stream is to use:

jq -s add

For the second problem, creating an array:

jq -s .

There are of course other alternatives, but these are simple and do not require the most recent version of jq. With jq 1.5 and later, you can use 'inputs', e.g. jq -n '[inputs]'

Efficient solution

For the first problem (reduction), rather than slurping (whether via the -s option, or using [inputs]), it would be more efficient to use reduce with inputs and the -n command-line option. For example, to combine the stream of objects into a single object:

jq -n 'reduce inputs as $in (null; . + $in)'

Equivalently, without --null-input:

jq 'reduce inputs as $in (.; . + $in)

Solution 2 - Arrays

An alternative to slurping using the -s command-line option is to use the inputs filter. Like so:

jq -n '[inputs] | add'

This will produce an object with all the input objects combined.

Solution 3 - Arrays

If you got to this point via jq filter rather than external input, mwag's comment suggesting wrapping your jq filter in []s might be useful.

Example:

$ echo '[{"foo":42},{"foo":43}]' | jq '.[]'
{
  "foo": 42
}
{
  "foo": 43
}
$ echo '[{"foo":42},{"foo":43}]' | jq '[.[]]'
[  {    "foo": 42  },  {    "foo": 43  }]

See also jq Github issue #684: Creating an array from objects?.

Solution 4 - Arrays

To combine objects into an array you can use the following:

$ echo '
{
  "a": "green",
  "b": "white"
}
{
  "a": "red",
  "c": "purple"
}' | jq -n '[inputs]'
[  {    "a": "green",    "b": "white"  },  {    "a": "red",    "c": "purple"  }]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJennifer M.View Question on Stackoverflow
Solution 1 - ArrayspeakView Answer on Stackoverflow
Solution 2 - ArraysEvgenyView Answer on Stackoverflow
Solution 3 - ArraysggorlenView Answer on Stackoverflow
Solution 4 - ArraysTrane9991View Answer on Stackoverflow