Reputation: 785
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?
Upvotes: 71
Views: 163392
Reputation: 11
My example bash command to replace an array in a json file. Everything is in variables:
a=/opt/terminal/conf/config.json ; \
b='["alchohol"]' ; \
c=terminal.canceledInspections.resultSendReasons ; \
cat $a | jq .$c ; \
cat $a | jq --argjson b $b --arg c $c 'getpath($c / ".") = $b' | sponge $a ; \
cat $a | jq .$c
Upvotes: 1
Reputation: 51
you can do this:
key="dev.projects.prj1"
filter=".$key"
cat config.json | jq $filter
Upvotes: 5
Reputation: 431
You can use --argjson
too when you make your json.
--arg a v # set variable $a to value <v>;
--argjson a v # set variable $a to JSON value <v>;
Upvotes: 42
Reputation: 361
As asked in a comment above there's a way to pass multiple argumets. Maybe there's a more elegant way, but it works.
jq --arg key1 $k1 --arg key2 $k2 --arg key3 $k3 --arg key4 $k4 '.[$key1] | .[$key2] | .[$key3] | .[$key4] '
jq --arg key $k ' if key != "" then .[$key] else . end'
jq --arg key $k ' if type == "array" then .[$key |tonumber] else .[$key] end'
of course you can combine these!
Upvotes: 25
Reputation:
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
Upvotes: 109