Logan Lee
Logan Lee

Reputation: 1007

How to correctly use jq's in() function

I'm trying to understand in() function of jq.

https://jqplay.org/s/BR1KbCjP8u

filter:
map( in(["ms", "is", "bad"]) )
input:
["apple","is","bad"]

I expected the output [false,true,true] because for each element of the input array:

  1. "apple" is not in ["ms", "is", "bad"] so false
  2. "is" is in ["ms", "is", "bad"] so true
  3. "bad" is in ["ms", "is", "bad"] so true

Obviously this is wrong because I get error:

jq: error (at <stdin>:0): Cannot check whether array has a string key
exit status 5

What is wrong with this and how to correctly use the in() function when passing ["ms","is","bad"] in the filter? I want to check if each element in the input array is found in this list.

Upvotes: 2

Views: 2829

Answers (2)

pmf
pmf

Reputation: 36541

Maybe you were looking for the IN (not in) function. Also, it takes a stream of elements, not an array.

map(IN("ms", "is", "bad"))
[false,true,true]

Demo


From the manual:

in

The builtin function in returns whether or not the input key is in the given object, or the input index corresponds to an element in the given array. It is, essentially, an inversed version of has.

IN

This builtin outputs true if . appears in the given stream, otherwise it outputs false.

Upvotes: 5

Logan Lee
Logan Lee

Reputation: 1007

I was using in() incorrectly.

https://jqplay.org/s/FJcNTgplG6

filter:
map(in(["apple","is","bad"]))
input:
[3, 2, 1, 0]
output:
[
  false,
  true,
  true,
  true
]

It's testing if the indexes of the filter array are found in the input array.

Upvotes: 1

Related Questions