Sum values with jq

12 Jan 2021 in TIL

Given a set of transactions in JSON format, I wanted to work out what the sum of a specific field was.

Here's a slimmed down version of the data:

json
{
"transactions": [
{
"date": "07/01/21",
"plAmount": "4,000.00"
},
{
"date": "03/01/21",
"plAmount": "8,800.00"
},
{
"date": "02/01/21",
"plAmount": "1,000.00"
},
{
"date": "28/12/20",
"plAmount": "2,500.00"
}
]
}

Here's how to sum the plAmount field from the above data:

bash
jq '[.transactions[].plAmount | gsub(",";"") | tonumber] | add'
# 16300

Step by Step

The first step is to extract the plAmount field from each entry:

bash
jq '.transactions[].plAmount'
# "4,000.00"
# "8,800.00"
# "1,000.00"
# "2,500.00"

Next, convert all of these values to numbers by removing the , and converting to integers

bash
jq '.transactions[].plAmount | gsub(",";"") | tonumber'
# 4000
# 8800
# 1000
# 2500

Convert it to a list of numbers by wrapping it in []:

bash
jq '[.transactions[].plAmount | gsub(",";"") | tonumber]'
# [
# 4000,
# 8800,
# 1000,
# 2500
# ]

Then finally call add to sum those values:

bash
jq '[.transactions[].plAmount | gsub(",";"") | tonumber] | add'
# 16300