Wednesday, October 27, 2021

[SOLVED] How to use key variables to get a second level value of json file using jq

Issue

I need to get a specific value from a json file using jq in a bash script (busybox). The json file looks like this:

{
  "example.com": {
    "backend": "1.3.7"
  }
}

In my script there are two variables: project and app - as there are of course multiple projects and applications. I need to use these variable values to get the version value. In this example project is "example.com" and app is "backend"

I tried this

jq --arg p "$project" --arg a "$app" '.[$p].[$a]' file.json

But I do get the error

jq: error: syntax error, unexpected '[', expecting FORMAT or QQSTRING_START (Unix shell quoting issues?) at <top-level>, line 1:
.[$p].[$a]      
jq: 1 compile error

Solution

You may use it like this:

jq -r --arg p "$project" --arg a "$app" '.[$p][$a]' file.json

or else:

jq -r --arg p "$project" --arg a "$app" '.[$p] | .[$a]' file.json
1.3.7


Answered By - anubhava