I have below JSON file and facing error when trying to add values to array dynamically in the shell.
Below is a tmp.json file,
{
"environments": {
"integration": [
"testing for jenkins job"
],
"prod": [],
"staging": [],
"uat": []
}
}
When I try to append values to an array with a static variable, it works fine. Below is the command, jq '.environments.integration += ["test1"]' tmp.json
The respective output is,
{
"environments": {
"appbuild": [],
"integration": [
"testing for jenkins job",
"test1"
],
"prod": [],
"staging": [],
"uat": []
}
}
Whereas when I try to append values dynamically, it throws an error.
export Environment_Name="integration"
jq ".environments."\"${Environment_Name}"\" += test1" tmp.json
Error I am getting is,
jq: error: test1/0 is not defined at <top-level>, line 1:
.environments."integration" += test1
jq: 1 compile error
Can anyone please help to fix this.
You have some extra quotes in there and test1
needs to be ["test1"]
jq ".environments.${Environment_Name} += [\"test1\"]" tmp.json
Using shell-based variable interpolation is usually a very bad idea. In the present case, what if the shell variable contains a double-quotation mark, for example?
The safe thing to do is to use env
or --arg
or --argjson
as appropriate, e.g.
jq --arg e "${Environment_Name}" '.environments[$e] += ["test1"]'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With