If I have a JSON like this,
{ "hello1": "world1", "testk": "testv" }
And I want to export each of these key-value pairs as environment variables, how to do it via shell script? So for example, when I write on the terminal, echo $hello1
, world1
should be printed and similarly for other key-value pairs? Note: The above JSON is present in a variable called $values
and not in a file.
I know it will be done via jq
and written a shell script for this, but it doesn't work.
for row in $(echo "${values}" | jq -r '.[]'); do -jq() { echo ${row} | jq -r ${1} } echo $(_jq '.samplekey') done
You have to wrap the environment variable of choice into another set of quotes in order for it to be valid JSON.
Export Environment Variable Export is a built-in shell command for Bash that is used to export an environment variable to allow new child processes to inherit it. To export a environment variable you run the export command while setting the variable. export MYVAR="my variable value"
Variables exist in memory/code only, and a variable can be written to JSON format in a file for example, but with the risk of sounding "blunt" IMHO, your question doesn't make much sense at this point. If you elaborate a little more on what you want to achieve in your application, I might be able to help you better.
export is a bash builtin; VAR=whatever is bash syntax. env , on another hand, is a program in itself. When env is called, following things happen: The command env gets executed as a new process.
Borrowing from this answer which does all of the hard work of turning the JSON into key=value pairs, you could get these into the environment by looping over the jq
output and export
ing them:
for s in $(echo $values | jq -r "to_entries|map(\"\(.key)=\(.value|tostring)\")|.[]" ); do export $s done
If the variables being loaded contain embedded whitespace, this is also reasonable, if slightly more complex:
while read -rd $'' line do export "$line" done < <(jq -r <<<"$values" \ 'to_entries|map("\(.key)=\(.value)\u0000")[]')
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