Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq doesn't work with keys which contains dash in it from a variable

Tags:

jq

If you'd like jq to escape dashes, you need to put your key between square brackets like this;

jq '.["key-key"]'

and apart from that, if you'd like to include a variable in jq, you need to use double quotes instead of single quotes;

jq "."${var[i+1]}""

but my variable contains dash in it and in this case, I've tried to merge the 2 examples above but it didn't work;

var=key-key
jq ".["${var[i+1]}"]."key""

how can I get this work?

Update:

This is the final script, which I've forgot to mention;

declare -a var=(
    "key-key"
    "key2-key2"
    "key3-key3"
)

for ((i=0; i<${#var[@]})); do
    curl -s "url" | jq ".["${var}"]."something""
done
like image 378
Marry Jane Avatar asked Feb 13 '19 16:02

Marry Jane


1 Answers

To have double-quotes in a jq command you've enclosed in double-quotes, you'd escape them with a backslash :

jq ".[\"key-key\"]"

Another problem with your final command is that ${var[i+1]} expands to the empty string, because this syntax is used to index elements of an array, and you previously defined var as a simple string.

A better way to work with variables in jq commands is to define them through the --arg name value option, after which you can refer to them with $foo in a single-quotes enclosed command :

jq --arg keyName key-key '.[$keyName]'

To fix the code included in the update, I would use the following :

declare -a var=(
    "key-key"
    "key2-key2"
    "key3-key3"
)

json=$(curl -s "url")

for searchedKey in "${var[@]}"; do
    echo $json | jq --arg keyName $searchedKey '.[$keyName].something'
done
like image 180
Aaron Avatar answered Oct 13 '22 21:10

Aaron