skip to Main Content

I have the following json:

[
  {
    "a": 10,
    "b": 20
  },
  {
    "a": 11,
    "c": 30,
  },
  {
    "b": 21,
    "c": 31
  }
]

And I need to create a new json object with all the keys in the different array entries, but with the accumulated values. Something like this:

{
  "a": 21,
  "b": 41,
  "c": 61
}

The array elements could be a lot more, and the keys could be anything.

How do I do that? Is that possible with jq, or maybe another tool?

2

Answers


  1. Assuming the array has only flat objects, you could use to_entries to iterate over their key-value pairs, and add them up in a reduce folding:

    reduce (.[] | to_entries[]) as {$key, $value} ({};
      .[$key] += $value
    )
    
    {
      "a": 21,
      "b": 41,
      "c": 61
    }
    

    Demo

    Login or Signup to reply.
  2. To round out your options, if you have an arbitrarily nested set of objects. Stream it selecting leaf values and you can take the last part of the path as the key.

    reduce (tostream|select(length==2)|.[0]|=last) as [$key, $value] ({};
      .[$key] += $value
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search