I'm using jq to parse JSON data and pull out a value based on a dynamic key value given as a command line argument. I noticed that this works, but I'm skeptical about how it's interpolating $v within the single quotes. Is it possible to rewrite the expression '.["\($v)"]' within double quotes? What am I doing wrong?
Trying the following doesn't work for whatever reason:
recipe_url=$(cat ./*.json | jq -r --arg v "$recipe_key" ".[\"\\($v)\"]")
However, this does:
recipe_key='Wilted Greens' # example key to interpolate
recipe_url=$(cat ./*.json | jq -r --arg v "$recipe_key" '.["\($v)"]') # works!
You have not escaped the $v, so Bash thinks it is a Bash variable, probably an empty one.
Try this
".[\"\\(\$v)\"]"
# ^
# |
# --- notice
In my opinion, it is better in this situation to use use --arg with single quotes. --arg was implemented similar to awk -v, to fix exactly this type of situation with quoting headaches.
I noticed that this works, but I'm skeptical about how it's interpolating $v within the single quotes.
Single quotes don't interpolate variables or evaluate anything else.
Nothing is magical within single quotes. You can't even escape single quotes within single quotes.
The quoting/escaping problem you are having exists only because you are attempting to use double quotes instead of single quotes here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With