Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help in reducing array of object into a single sum

Tags:

shell

jq

In shell script, I have below array of object:

response={
        "product": "BIG MAC",
        "objects": [
                        {
                            "qty": 10,
                            "size": 32
                        },
                        {
                            "qty": 20,
                            "size": 53
                        },
                        {
                            "qty": 10,
                            "size": 54
                        }
        ]
    }

I am writing a jq function to get total quantity.

data=$( echo $response | jq '.objects[] | .qty ' )

This gives me one line of quantities, like

10 20 10

How do I sum these to get value:

40
like image 927
uday8486 Avatar asked Nov 18 '19 15:11

uday8486


Video Answer


1 Answers

Create an array and pipe that through add:

jq '[.objects[] | .qty] | add'

Using map might make this simpler, as you don't have to "index" .objects first:

jq '.objects | map(.qty) | add'
like image 94
chepner Avatar answered Sep 28 '22 04:09

chepner