skip to Main Content

I have similar file/data:

$ echo "[{"my_var1":"valueA", "my_var2": "valueB"}]"
{"my_var1":"valueA", "my_var2": "valueB"}]

in my code I need to get value of "my_var2", easy:

$ echo "[{"my_var1":"valueA", "my_var2": "valueB"}]" | 
jq -r '.[] .my_var2'

# correct result:
valueB

… but … I need to use bash variable to specify which variable I would like to get:

I can’t specify "my_var2", I have to use only "var2"

$ PART="var2"
$ echo "[{"my_var1":"valueA", "my_var2": "valueB"}]" | 
jq -r --arg JSONPART ${PART} '.[] .my_[$JSONPART]'

expected result:

valueB

2

Answers


  1. This should work:

    $ PART="var2"
    $ echo "[{"my_var1":"valueA", "my_var2": "valueB"}]" | 
    jq -r ".[] .my_$PART"
    
    Login or Signup to reply.
  2. The jq filter .xyz can be rewritten as .["xyz"]. Thus:

    $ PART='var2'
    $ echo '[{"my_var1":"valueA", "my_var2": "valueB"}]' | 
    jq -r --arg JSONPART "$PART" '.[]["my_" + $JSONPART]'
    valueB
    

    (Don’t forget to properly quote your shell parameters when expanding!)

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