I have the following json file
{
"result": {
"run": {
"runtime": "runc"
},
"software": {
"runc": "1.1.2",
"kata": "1.3.7"
}
}
}
I can extract the runtime info using this
# jq -r '.result.software .runc' input.json
1.1.2
However, if I try to extract the version number dynamically, it does not work (The runtime can change)
# runtime=$(jq -r '.result.run .runtime' input.json)
# jq --arg key "$runtime" '.result.software .[$key]'
jq: error: syntax error, unexpected '[', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
.result.software .[$key]
jq: 1 compile error
CodePudding user response:
The combined dot notation only works with literal names. Use .result.software[$key]
instead:
runtime="$(jq -r '.result.run.runtime' input.json)"
jq -r --arg key "$runtime" '.result.software[$key]'
1.1.2
If the dynamic value is always a result of evaluating the same JSON file, and you don't need that value elsewhere in the shell script, you can resolve that internally and reduce the script to just one call to jq:
jq -r '.result.run.runtime as $key | .result.software[$key]' input.json
Or without using variables at all:
jq -r '.result | .software[.run.runtime]' input.json
Note: Never use double quotes to inject data into code. --arg
is always a better choice.
CodePudding user response:
Use double quotes to extract variables:
RUNTIME=$(jq -r ".result.run .runtime" input.json)
VERSION=$(jq -r ".result.software .$RUNTIME" input.json)
echo "${RUNTIME} @ ${VERSION}"
I'd rather wonder were those square brackets even come from?
There's no array access: [$VAR]
, but it's string ${VAR}
or $VAR
.