将JSON导出到环境变量

编程入门 行业动态 更新时间:2024-10-25 10:33:58
本文介绍了将JSON导出到环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我有这样的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导出到环境变量

本文发布于:2023-11-24 09:15:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1624623.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:环境变量   导出到   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!