skip to Main Content

Let’s say I have a few JSON objects in a Bash variable :

json='{"key":"100"}{"key":"200"}{"key":"300"}'

To select the object with key matching 100 I can do :

printf '%sn' "$json" | jq 'select ( .key == "100" )'

As @axiac pointed out in the comments, I can use or to match one of several values.

printf '%sn' "$json" | jq 'select(.key == "100" or .key == "200")

But what if I need to match key against a larger number of values, in which case using or becomes cumbersome?

What code would select all objects with key matching a value between 99 and 201?

2

Answers


  1. select all objects with key matching a value between 99 and 201?

    Interpreting "between" as "strictly between", one way would be:

     select(.key | tonumber | IN(range(100;200)))
    

    Or more efficiently, instead of IN, use the condition:

      99<. and .<201
    
    Login or Signup to reply.
  2. printf '%sn' "$json" |jq 'select((.key|tonumber >=100) and (.key|tonumber <=200))'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search