r123454321
r123454321

Reputation: 3403

Using jq to extract values in JSON array with a particular key boolean == true?

So I have a JSON blob as below:

[
  {
    '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?

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:

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

Upvotes: 24

Views: 31461

Answers (3)

hmedia1
hmedia1

Reputation: 6180

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. 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 will compare the value as desired;

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

or for an exact match, slight variant:

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

Upvotes: 11

peak
peak

Reputation: 116680

If the task is to "print the IDs of all entries in the array that have isSparse == true", an appropriate jq filter would be:

.[] | 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:

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

As @JeffMercado pointed out, if .isSparse is strictly boolean, then select(.isSparse) would suffice.

Upvotes: 24

Jeff Mercado
Jeff Mercado

Reputation: 134811

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

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

Upvotes: 6

Related Questions