简体   繁体   English

如何使用 jq 返回过滤数组的长度?

[英]How to use jq to return length of filtered array?

My json file is called my_locations.json and contains an array called locations .我的 json 文件名为my_locations.json并包含一个名为locations的数组。 I want to filter this array by all objects that have keys location.is_shop and location.has_parking_space .我想通过具有键location.is_shoplocation.has_parking_space的所有对象来过滤此数组。 I then want to return the length of this filtered array.然后我想返回这个过滤后的数组的长度。

Here is my attempt using the program jq :这是我使用程序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.所以它输出的是数组中每个位置object的长度,而不是过滤后数组的长度。

How can I return the length of the filtered array?如何返回过滤后数组的长度?

Function map is what you need: Function map是你需要的:

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.我认为你应该使用 function has ,因为你想测试键的existence ,而不是值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM