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
Edit: Trying Turn's answer, I did this:
values='{"hello1":"world1","hello1.world1.abc1":"hello2.world2.abc2","testk":"testv"}'
for s in $(echo $values | jq -r "to_entries|map(\"\(.key)=\(.value|tostring)\")|.[]" ); do
export $s
done
The approach illustrated by the following shell script avoids most (but not all) problems with special characters:
Note that the above assumes that there are no tabs in the keys themselves.
In order to achieve this, you can use
jq
which is a lightweight and flexible command-line JSON processor.Let's say you have your environment variables in a file called
environment.json
as follows:You can employ the following script to export them:
You can verify your variables have been aded by either using:
or
Using command substitution
$()
:Edit : Responding to this comment
You should do
Just mind the
double
quotes around$values
Note: Couldn't confirm if there is security implication to this approach, that is if the user could manipulate the
json
to wreak havoc.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 andexport
ing them: