简体   繁体   中英

Using jq with bash variables results in error

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

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 .

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

Demo

Or without using variables at all:

jq -r '.result | .software[.run.runtime]' input.json

Demo

Note: Never use double quotes to inject data into code. --arg is always a better choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM