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
Assuming the array has only flat objects, you could use
to_entries
to iterate over their key-value pairs, and add them up in areduce
folding:Demo
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.