jq is a powerful tool to work with JSON from the command-line. The tool has a lot of functions that makes our live easier. One of the functions is add which adds all elements in an array or values in an object. The function has no arguments. The elements in an array are added together if they are numbers and concatenated if they are strings. If the input is an object then the values are added together. When the input is an empty array or object then null is returned.

In the following examples we see different usages of the add function:

$ jq --null-input '[1, 2, 3, 4,] | add'
10
$ jq --null-input '["a", "b", "c", "d"] | add'
"abcd"
$ jq --null-input '{ "burger": 3.23, "drinks": 2.89 } | add'
6.12
$ jq --null-input '[] | add'
null

Written with jq 1.7.

shadow-left