I want to loop through a JSON object and add the keys and values to a Bash associative array.
Here’s my JSON object that is in a file named deploy.json
.
"deploymentEnvs": {
"dev": "zone_dev",
"test": "zone_test",
"prod": "zone_prod"
}
I want to take the keys and values and add them to a Bash associative array, something like this:
declare -A deployenvs
deployenvs[dev]="zone_dev"
deployenvs[test]="zone_test"
deployenvs[prod]="zone_prod"
So far I have this command jq -r 'to_entries|map("(.key)=(.value|tostring)")|.deploymentEnvs' deploy.json
. When I run it I get a jq error stating `Cannot index array with string “deploymentEnvs”. I couldn’t find a StackOverflow post that specifically applied to my situation. I figured I need to do some kind of while loop using the above jq command but I’m stuck on how to do it. Any help would be appreciated.
A JSON array is not a Bash array. Construct the Bash array using declare
, and have jq
print the declaration the way Bash requires it.
- using the traditional
[key]=value
format
declare -A deployenvs="($(
jq -r '.deploymentEnvs | to_entries[] | @sh "[(.key)]=(.value)"' deploy.json
))"
- or using the newer
key value
format:
declare -A deployenvs="($(
jq -r '.deploymentEnvs | to_entries[] | .key, .value | @sh' deploy.json
))"
Both will generate an associative array in Bash:
declare -p deployenvs
declare -A deployenvs=([prod]="zone_prod" [dev]="zone_dev" [test]="zone_test" )
2