Exporting JSON to environment variables

2019-02-24 13:12发布

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

4条回答
相关推荐>>
2楼-- · 2019-02-24 13:23

The approach illustrated by the following shell script avoids most (but not all) problems with special characters:

#!/bin/bash

function json2keyvalue {
   cat<<EOF | jq -r 'to_entries|map("\(.key)\t\(.value|tostring)")[]'
{
    "hello1": "world1",
    "testk": "testv"
}
EOF
}

while IFS=$'\t' read -r key value
do
    export "$key"="$value"
done < <(json2keyvalue)

echo hello1="$hello1"
echo testk="$testk"

Note that the above assumes that there are no tabs in the keys themselves.

查看更多
▲ chillily
3楼-- · 2019-02-24 13:25

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:

# environment.json
{
    "hello1": "world1",
    "testk": "testv"
}

You can employ the following script to export them:

for s in $(jq -r "to_entries|map(\"\(.key)=\(.value|tostring)\")|.[]" environment.json); do
    export $s
done

You can verify your variables have been aded by either using:

printenv

or

echo $VARIABLE_NAME # use the name of your environment variables instead
查看更多
ら.Afraid
4楼-- · 2019-02-24 13:31

Using command substitution $() :

# $(jq -r 'keys[] as $k | "export \($k)=\(.[$k])"' file.json)
# echo $testk
testv

Edit : Responding to this comment

You should do

$( echo "$values" | jq -r 'keys[] as $k | "export \($k)=\(.[$k])"' )

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.

查看更多
孤傲高冷的网名
5楼-- · 2019-02-24 13:36

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
查看更多
登录 后发表回答