skip to Main Content

Running the below:

$ echo '["lorem", "ipsum", "dolor"]' | jq '. | contains(["rem"])' 

returns true because "rem" is a substring of "lorem". I would like a whole word match, which would disqualify "rem" and only allow one of the three values in the input.

$ echo '["lorem", "ipsum", "dolor"]' | jq 'select(. | index("rem"))'

returns nothing at all, but jq exits cleanly. I would have expected a false.

How do I get a boolean value for whole word match?

2

Answers


  1. You want to receive true if any (=at least one) of the items equals (==) a given value:

    $ echo '["lorem", "ipsum", "dolor"]' | jq 'any(. == "lorem")'
    true
    
    $ echo '["lorem", "ipsum", "dolor"]' | jq 'any(. == "rem")'
    false
    

    In other words, you want to receive true if a given value is contained IN a set of items .[]:

    $ echo '["lorem", "ipsum", "dolor"]' | jq 'IN(.[]; "lorem")'
    true
    
    $ echo '["lorem", "ipsum", "dolor"]' | jq 'IN(.[]; "rem")'
    false
    
    Login or Signup to reply.
  2. I’ve tripped over this many times before as well, as you’d expect it to work like this out of the box.

    But the answer (if you’re after a chainable exit code) is: use the -e flag, which, according to man jq:

    Sets the exit status of jq to 0 if the last output values was
    neither false nor null, 1 if the last output value was either false or
    null, or 4 if no valid result was ever produced. Normally jq
    exits with 2 if there was any usage problem or system error, 3 if
    there was a jq program compile error, or 0 if the jq program ran.

    So you’d want jq -e 'select(. | index("rem"))'

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search