jq how to merge array objects into single object

Viewed 625

in jq its possible to add objects using the + operator

if you have an array

 [
      {
        "a": "value"
      },
      {
        "b": "value"
      },
      {
        "c": "value"
      }
 ]

I want to convert it into a single object { a:"value", b:"value", c:"value" } I can use the following filter .[0] + .[1] + .[2], but i want to do it for the whole array without specifying all the indexes.

3 Answers

You can use reduce:

reduce .[] as $o ({}; . + $o)

returns:

{
  "a": "value",
  "b": "value",
  "c": "value"
}

The simplest way is just to call add filter.

"The filter add takes as input an array, and produces as output the elements of the array added together. This might mean summed, concatenated or merged depending on the types of the elements of the input array - the rules are the same as those for the + operator (described above)."


Source: https://stedolan.github.io/jq/manual/#add

$ cat test.json 
[ 
    {
        "a": "value"
    },
    {
        "b": "value"
    },
    {
        "c": "value"
    }
 ]

$ jq 'add' test.json
{
  "a": "value",
  "b": "value",
  "c": "value"
}

As mentioned by peak in the comment, you can even skip wrapping add filter with the quotes:

$ jq add test.json
{
  "a": "value",
  "b": "value",
  "c": "value"
}

In case you want to merge all objects in array recursively (didn't find any similar answer here):

jq 'reduce .[] as $x ({}; . * $x)'
Related