Home > Software design >  Use any() to check if certain key exists in JQ
Use any() to check if certain key exists in JQ

Time:05-01

I want to use jq to check if a keyword exists as a key in a JSON at any level. Here is what I came up with:

jq -c 'paths | select(.[-1]) as $p| index("headline") //empty' news.json

The output is an array:

[
  6,
  7,
  9
]

I want to map the output array to jq function any() and get an overall result as true if key exists or false if it doesn't.

How can I get that done with jq ?

CodePudding user response:

Provide any with an iterator and a condition

jq 'any(paths; .[-1] == "headline")'

You can also provide the -e (or --exit-status) option to have an exit status of 0 if the result was true, and 1 if the result was false, which can immediately be used for further processing in the shell.

jq -e 'any(paths; .[-1] == "headline")'

CodePudding user response:

You don't need an intermediate array for that.

any(paths[-1]; . == "headline")
  • Related