Jia
Jia

Reputation: 2581

Use any() to check if certain key exists in JQ

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 ?

Upvotes: 1

Views: 5490

Answers (2)

oguz ismail
oguz ismail

Reputation: 50750

You don't need an intermediate array for that.

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

Upvotes: 1

pmf
pmf

Reputation: 36088

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")'

Upvotes: 2

Related Questions