Sum values with jq
Output the sum of a set of values by extracting a single field, converting to a number and adding them all together
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:
{
"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:
jq '[.transactions[].plAmount | gsub(",";"") | tonumber] | add'
# 16300
Step by Step
The first step is to extract the plAmount
field from each entry:
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
jq '.transactions[].plAmount | gsub(",";"") | tonumber'
# 4000
# 8800
# 1000
# 2500
Convert it to a list of numbers by wrapping it in []
:
jq '[.transactions[].plAmount | gsub(",";"") | tonumber]'
# [
# 4000,
# 8800,
# 1000,
# 2500
# ]
Then finally call add
to sum those values:
jq '[.transactions[].plAmount | gsub(",";"") | tonumber] | add'
# 16300