Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpolating Strings Using jq

Tags:

linux

bash

jq

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!
like image 987
theGrayFox Avatar asked Jun 29 '26 14:06

theGrayFox


2 Answers

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.

like image 195
Zombo Avatar answered Jul 02 '26 04:07

Zombo


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.

like image 30
Etan Reisner Avatar answered Jul 02 '26 04:07

Etan Reisner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!