Dean Mraz

I am passionate about delivering ideas and spending most of my time on product management techniques.

February 4th 2017

Totaling JSON Attribute

Consuming JSON APIs can be challenging. jq is a light weight command line tool to parse json. It can solve problems like totaling a json attribute so you don't have to do it manually.

Goal

Sum the total attribute in each requestReport object.

example data set

{
    "requestReports": [
        {
            "id": "1",
            "total": "1"
        }, 
        {
            "id": "2",
            "total": "3"
        },
        {
            "id": "3",
            "total": "5"
        }
    ]
}

jq reduce

jq '.requestReports | reduce .[] as $item (0; . + ($item.total|tonumber)) '

jq play ground example

https://jqplay.org/s/JJ2fqpEHib

References