Philipp
Philipp

Reputation: 23

jq get number of jsons in an array containing a specific value

I've got an array of multiple JSON. I would like to get the number of of JSON which contain a specific value.

Example:

[
 {
  "key": "value1",
  "2ndKey":"2ndValue1"
 },
 {
  "key": "value2",
  "2ndKey":"2ndValue2"
 },
 {
  "key": "value1",
  "2ndKey":"2ndValue3"
 }
]

So in case I'm looking for value1 in key, the result should be 2.

I would like to get an solution using jq. I had already some tries, however they did not fully work. The best one yet was the following:

cat /tmp/tmp.txt | jq ' select(.[].key == "value1" ) | length ' 

I get the correct results but it is shown multiple times.

Can anybody help me to further improve my code. Thanks in advance!

Upvotes: 1

Views: 91

Answers (2)

peak
peak

Reputation: 116919

An efficient and convenient way to count is to use 'count' as defined below:

def count(s; cond): reduce s as $x (0; if ($x|cond) then .+1 else . end);
count(.[]; .key == "value1")

Upvotes: 1

jq170727
jq170727

Reputation: 14705

You are pretty close. Try this

map(select(.key == "value1")) | length

or the equivalent

[ .[] | select(.key == "value1") ] | length

Upvotes: 1

Related Questions