如果我有这样的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推荐答案
从此答案,它完成了将JSON转换为key = value对的所有艰苦工作,您可以通过循环jq输出和export添加它们:
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更多推荐
将JSON导出到环境变量
发布评论