Issue
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.
Solution
You have some extra quotes in there and test1
needs to be ["test1"]
jq ".environments.${Environment_Name} += [\"test1\"]" tmp.json
Answered By - Stefan Answer Checked By - Clifford M. (WPSolving Volunteer)