Markus
Markus

Reputation: 1965

How to use jq to select from value array

I have data like this:

$ cat foo.json
{"s1": [{"answer": 1, "count": 90}, {"answer": 0, "count": 10}]}
{"s2": [{"answer": 1, "count": 85}, {"answer": 0, "count": 15}]}

I'm trying to use jq to extract the count of the 1 answer for each key, with this desired result:

{"s1": 90, "s2": 85}

Update -- this result would be equally useful:

{"s1": 90}
{"s2": 85}

How can I do that with jq?

Upvotes: 0

Views: 55

Answers (2)

choroba
choroba

Reputation: 242123

This gives the originally requested result:

jq -s '[ .[]
         | .[] = (.[][])
         | select(.[].answer == 1)
         | .[] = .[].count
       ] | add' foo.json

Upvotes: 1

Markus
Markus

Reputation: 1965

Looks like this solution works:

jq -c 'with_entries(.value = (.value[] | select(.answer==1) | .count))' foo.json
{"s1":90}
{"s2":85}

There may be a more elegant way to do this.

Upvotes: 0

Related Questions