jq - count number of items matching select

Viewed 917

I am trying to count the number of records that match some property.

If I have json like:

[
  {
    "id": 0,
    "count": 1
  },
  {
    "id": 1,
    "count": 1
  },
  {
    "id": 2,
    "count": 0
  }
]

I am trying to get the number of records with a count of 1.

I can get the matching records with:

$ jq '.[] | select(.count == 1)' in.json
{
  "id": 0,
  "count": 1
}
{
  "id": 1,
  "count": 1
}

But the output lists two items, so I cannot directly use length to count them. Instead, using length gives the length of each item.

$ jq '.[] | select(.count == 1) | length' in.json
2
2

How can I count how many records were matched by select?

2 Answers

For efficiency, one should avoid using length on a constructed array. Instead, it's preferable to use a stream-oriented approach.

Here's one efficient solution, which, for convenience, uses the generic count function, defined as:

def count(stream): reduce stream as $i (0; .+1);

With this def, the solution is simply:

count(.[] | select(.count==1))
Related