将JSON导出到环境变量 [英] Exporting JSON to environment variables
问题描述
如果我有这样的JSON
If I have a JSON like this,
{
"hello1": "world1",
"testk": "testv"
}
我想将每个键-值对导出为环境变量,如何通过shell脚本来实现?因此,例如,当我在终端上书写时,应该打印echo $hello1
,world1
,并且对于其他键值对也应类似地打印?
注意:上面的JSON存在于名为$values
的变量中,而不存在于文件中.
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.
我知道这将通过jq
完成,并为此编写了一个shell脚本,但这是行不通的.
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
尝试Turn的答案,我做到了:
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
推荐答案
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
这篇关于将JSON导出到环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!