Home > Enterprise >  How to use jq to return length of filtered array?
How to use jq to return length of filtered array?

Time:01-28

My json file is called my_locations.json and contains an array called locations. I want to filter this array by all objects that have keys location.is_shop and location.has_parking_space. I then want to return the length of this filtered array.

Here is my attempt using the program jq:

$ jq ".locations[] | select(.is_shop and .has_parking_space) | length" my_locations.json
13
13
13
13
13
...
13

So it outputs the length of each location object in the array instead of the length of the filtered array.

How can I return the length of the filtered array?

CodePudding user response:

Function map is what you need :

jq '.locations | map(select(has("is_shop") and has("has_parking_space"))) | length' my_locations.json

I think you should use function has, because you want to test existence of the keys, not the value.

  • Related