Reducing JSON with jq Reducing JSON with jq unix unix

Reducing JSON with jq


Note that jq has a builtin function called 'add' that the same thing that the first answer suggests, so you ought to be able to write:

jq add myjson.json


To expand on the other two answers a bit, you can "add" two objects together like this:

.[0] + .[1]=> { "key1": "value", "key2": "value" }

You can use the generic reduce function to repeatedly apply a function between the first two items of a list, then between that result and the next item, and so on:

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

We start with {}, add .[0], then add .[1] etc.

Finally, as a convenience, jq has an add function which is essentially an alias for exactly this function, so you can write the whole thing as:

add

Or, as a complete command line:

jq add myjson.json


I believe the following will work:

cat myjson.json | jq 'reduce .[] as $item ({}; . + $item)'

It takes each item in the array, and adds it to the sum of all the previous items.