How to select items in JQ based on value in array

On Jan 30, 2017, a builtin named IN was added for efficiently testing whether a JSON entity is contained in a stream. It can also be used for efficiently testing membership in an array. In the present case, the relevant usage would be:

select( .items as $items | "blue" | IN($items[]) )

If your jq does not have IN/1, then so long as your jq has first/1, you can use this equivalent definition:

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

any/0

Using any/0 here is relatively inefficient, e.g. compared to using any/1:

select( any( .items[]; . == "blue" ))

(In practice, index/1 is usually fast enough, but its implementation currently (jq 1.5 and versions through at least July 2017) is suboptimal.)


Found out the answer

jq 'select(.items | index("blue"))'

Tags:

Json

Jq