Reputation: 1393
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
Upvotes: 5
Views: 70
Reputation: 116900
Using a stream-oriented addition function yields a solution that avoids the inefficiencies of constructing an array:
def sigma(s): reduce s as $x (0; .+$x);
sigma(.objects[] | .qty)
sigma
as defined here is a good candidate for your "standard library" of jq functions.
Upvotes: 2
Reputation: 531948
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'
Upvotes: 5