passing arguments to jq filter

lisi4ok picture lisi4ok · Jan 12, 2016 · Viewed 45k times · Source

Here is my config.json:

{
    "env": "dev",
    "dev": {
        "projects" : {
            "prj1": {
                "dependencies": {},
                "description": ""
            }
        }
    }
}

Here are my bash commands:

PRJNAME='prj1'

echo $PRJNAME

jq --arg v "$PRJNAME" '.dev.projects."$v"' config.json 
jq '.dev.projects.prj1' config.json 

The output:

prj1
null
{
  "dependencies": {},
  "description": ""
}

So $PRJNAME is prj1, but the first invocation only outputs null.

Can someone help me?

Answer

user3899165 picture user3899165 · Jan 12, 2016

The jq program .dev.projects."$v" in your example will literally try to find a key named "$v". Try the following instead:

jq --arg v "$PRJNAME" '.dev.projects[$v]' config.json