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
This should work:
The jq filter
.xyz
can be rewritten as.["xyz"]
. Thus:(Don’t forget to properly quote your shell parameters when expanding!)