[英]Using jq to extract values in JSON array with a particular key boolean == true?
So I have a JSON blob as below: 所以我有一个JSON blob如下:
[
{
'id': 'something',
'isSparse': true
},
...
]
How do I write a jq
command that'll filter out this JSON blob and print me the IDs of all entries in the array that have isSparse == true? 如何编写一个
jq
命令来过滤掉这个JSON blob并打印出数组中所有具有isSparse == true的条目的ID?
I tried the following: 我尝试了以下方法:
cat <blob> | jq -c '.[] | select(.operational | contains("true"))'
but get the following, because obviously true
is a boolean and not a string: 但得到以下内容,因为显然
true
是布尔值而不是字符串:
jq: error: boolean and string cannot have their containment checked
. jq: error: boolean and string cannot have their containment checked
。
If the task is to "print the IDs of all entries in the array that have isSparse == true", an appropriate jq filter would be: 如果任务是“打印数组中所有具有isSparse == true的条目的ID”,则适当的jq过滤器将是:
.[] | select(.isSparse == true) | .id
If there is any possibility of duplicate .id values, then the following could be used to ensure only distinct values are emitted: 如果存在重复.id值的任何可能性,则可以使用以下内容来确保仅发出不同的值:
map( select(.isSparse == true) | .id ) | unique[]
As @JeffMercado pointed out, if .isSparse is strictly boolean, then select(.isSparse) would suffice. 正如@JeffMercado指出的那样,如果.isSparse是严格的布尔值,则select(.isSparse)就足够了。
I add this answer as it may be helpful in future for a related scenario. 我添加这个答案,因为它可能有助于将来的相关场景。 - A specific example of this would be accessing a poorly written API which returns the same key/value pair differently depending on which endpoint or filters were used.
- 这方面的一个具体示例是访问写得不好的API,该API根据使用的端点或过滤器不同地返回相同的键/值对。 This is highly annoying when interfacing, and the value is a string sometimes and a boolean at other times (furthermore, sometimes even a number, or a number as a string :| )
接口时这非常烦人,有时候是一个字符串,有时候是一个布尔值(此外,有时甚至是一个数字,或者一个数字作为字符串:|)
Adding | tostring
添加
| tostring
| tostring
will compare the value as desired; | tostring
会根据需要比较值;
cat <blob> | jq -c '.[] | select(.isSparse | tostring | contains("true"))'
or for an exact match, slight variant: 或完全匹配,轻微变体:
cat <blob> | jq -c '.[] | select((.isSparse | tostring) == "true")'
I assume you mean isSparse
. 我猜你的意思是
isSparse
。 The select
filter takes in something that evaluates to a boolean value. select
过滤器接受一个计算为布尔值的东西。 isSparse
is already a boolean so you just need to select it. isSparse
已经是一个布尔值,所以你只需要选择它。 contains
is used for checking if something is in another container (a string, array, object, etc.). contains
用于检查是否有东西在另一个容器中(字符串,数组,对象等)。
$ jq -c '.[] | select(.isSparse)' <blob>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.