Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting JSON to environment variables

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 
like image 675
Qirohchan Avatar asked Jan 30 '18 02:01

Qirohchan


People also ask

Can JSON use environment variables?

You have to wrap the environment variable of choice into another set of quotes in order for it to be valid JSON.

What is export in environment variable?

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"

Can I use variable in JSON file?

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.

What is the difference between Env and export?

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.


1 Answers

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 exporting 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")[]') 
like image 59
Turn Avatar answered Sep 16 '22 17:09

Turn