Dark theme | Light theme

October 3, 2023

jq Joy: Sum Of Elements In An Array Or Object

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'
$ jq --null-input '["a", "b", "c", "d"] | add'
$ jq --null-input '{ "burger": 3.23, "drinks": 2.89 } | add'
$ jq --null-input '[] | add'

Written with jq 1.7.