Reputation: 227
I have an input json as below with the keys changing dynamically, the only static content in the key is the text '_GROUP_NAME' and '_VERSION'
[
{
"PREPROCESS_GROUP_NAME": "preprocess-group-name",
"PREPROCESS_VERSION": 2
},
{
"CLASSIFIER_GROUP_NAME": "classifier-group-name",
"CLASSIFIER_VERSION": 2
},
{
"ABC_GROUP_NAME": "abc-group-name",
"ABC_VERSION": 2
}
]
I want to export the key value pair as environment variables. Basically I want to read the json above and execute commands as
export PREPROCESS_GROUP_NAME='preprocess-group-name'
export PREPROCESS_VERSION=2
export CLASSIFIER_GROUP_NAME='classifier-group-name'
export CLASSIFIER_VERSION=2
export ABC_GROUP_NAME='abc-group-name'
export ABC_VERSION=2
I am looking for a solution which will create export commands based on dynamically generated keys and values.
Upvotes: 2
Views: 342
Reputation: 116967
With your JSON as input,
jq -r '.[] | to_entries[] | "export \(.key)=\(.value|@sh)"'
produces:
export PREPROCESS_GROUP_NAME='preprocess-group-name'
export PREPROCESS_VERSION=2
export CLASSIFIER_GROUP_NAME='classifier-group-name'
export CLASSIFIER_VERSION=2
These commands can then be evaluated by the shell in whichever way you deem appropriate.
A possibly-safer alternative would be:
while read -r key ; do
read -r value
export "$key"="$value"
done < <(< input.json jq -r '.[] | to_entries[] | .key, .value')
Upvotes: 4