Getting a list of keys based on another property in json with jq

I am trying to create a jq filter for JSON similar to How to filter an array of objects based on the values ​​in an internal array with jq? - but even using that as a basis doesn't seem to give me the results I want.

Here is my json example

[{"id":"0001","tags":["one","two"]},{"id":"0002", "tags":["two"]}]

      

I want to return a list of ids where the tags contain "one" (not a partial string match, a full element match).

I have tried some options but cannot filter correctly.

. - map(select(.resources[] | contains("one"))) | .[] .id

      

Returns "0001","0002"

Tried it ... .resources[].one)) | ...

, but always got the full list when trying to filter one by one and expected to get only0001

Where am I filtering wrong? (there are about 30 minutes of experience with jq, so please excuse my ignorance if this is something obvious :)

+3


source to share


1 answer


map(select(.tags | index("one")) | .id)

      

Since your description of the problem indicates that you want to check if the array contains "one", it is easiest to use an index.

UPDATE

On January 30, 2017, a named inline user was added IN

to effectively test whether a JSON object is contained in a stream. It can also be used to effectively test array membership. In this case, the corresponding usage would be:



map(select(.tags as $tags | "one" | IN($tags[])) | .id)

      

If your jq does not IN/1

, then as long as your jq does first/1

, you can use this equivalent definition:

def IN(s): . as $in | first(if (s == $in) then true else empty end) // false;

      

( index/1

Usually fast enough in practice , but its implementation at this time (jq 1.5 and versions at least July 2017) is suboptimal.)

+5


source







All Articles