Using jq to retrieve values ​​in a JSON array with a specific key boolean == true?

So I have a blob JSON as shown below:

[ { 'id': 'something', 'isSparse': true }, ... ] 

How to write a jq command that will filter out this piece of JSON and print me the identifiers of all the entries in the array with isSparse == true?

I tried the following:

cat <blob> | jq -c '.[] | select(.operational | contains("true"))'

but we get the following, because obviously true is logical, not string:

jq: error: boolean and string cannot have their containment checked .

+6
source share
3 answers

If the task is to "print out the identifiers of all the entries in the array with isSparse == true", the appropriate jq filter will be:

 .[] | select(.isSparse == true) | .id 

If it is possible to duplicate .id values, then to ensure that only individual values ​​are emitted, you can use the following:

 map( select(.isSparse == true) | .id ) | unique[] 

As @JeffMercado noted, if .isSparse is strictly logical, then select (.isSparse) will be enough.

+8
source

I am adding this answer as it may be useful in the future for the corresponding scenario. - A concrete example of this may be access to a poorly written API that returns the same key / value pair in different ways depending on which endpoint or filters were used. This is very annoying in the interaction, and the value is sometimes a string and a Boolean at another time (moreover, sometimes even a number or a number as a string: |)


Adding | tostring | tostring will compare the value as desired;

cat <blob> | jq -c '.[] | select(.isSparse | tostring | contains("true"))'

or for exact match, a small option:

cat <blob> | jq -c '.[] | select((.isSparse | tostring) == "true")'

+4
source

I assume you mean isSparse . The select filter takes a value that evaluates to a boolean value. isSparse already logical, so you just need to select it. contains used to verify that something is in another container (string, array, object, etc.).

 $ jq -c '.[] | select(.isSparse)' <blob> 
+2
source

All Articles