I have a list of credit card transactions. I would like to sum the Amount from the stream of JSON transactions. Each object contains data for 1 transaction. I use JQ to process JSON.
I have referenced this question: How do I sum the values in an array of maps in jq?
However after implementing the solution described in the question.
jq -n '
reduce (inputs | to_entries[]) as {$key,$value} ({}; .[$key] += $value)
' input.json
I noticed that the first number is not included in the addition. Below find sample file, output of command, and expected result
Sample File CC Transactions "jqAdditionSample.json"
{
"Originating Account Number": "####-####-####-0000",
"Cardholder Name": "NAME ON CARD",
"Merchant Name": "VENDOR NAME",
"Amount": 342.75,
"MCC Description": "Computer Software"
}
{
"Originating Account Number": "####-####-####-0000",
"Cardholder Name": "NAME ON CARD",
"Merchant Name": "VENDOR NAME",
"Amount": 492.71,
"MCC Description": "Computer Software"
}
{
"Originating Account Number": "####-####-####-0000",
"Cardholder Name": "NAME ON CARD",
"Merchant Name": "VENDOR NAME",
"Amount": 573,
"MCC Description": "Computer Software"
}
Expected Actual Total
Add the Amounts manually to find total 342.75+492.71+573=1408.46
Run the command
cat ~/Desktop/jqAdditionSample.json | \
jq 'reduce (inputs | to_entries[]) as {$key,$value} ({}; .[$key] += $value)'
Result:
{
"Originating Account Number": "####-####-####-0000####-####-####-0000",
"Cardholder Name": "NAME ON CARDNAME ON CARD",
"Merchant Name": "VENDOR NAMEVENDOR NAME",
"Amount": 1065.71,
"MCC Description": "Computer SoftwareComputer Software"
}
Note Discrepancy
The output 1065.71 adds sums all numbers except the first number. We can verify by subtracting 342.75 from expected value 1408.46. I want it to sum all numbers
In fact, no data from the first object is included in the sum.
Where I need help
Is there a way to make JQ sum all numbers from a field in a stream, am I doing something wrong?
Is there an easier method to sum all numbers for a field in JSON stream where I am taking the hard route?