bash 将 JSON 导出到环境变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48512914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:47:34  来源:igfitidea点击:

Exporting JSON to environment variables

jsonbashshellenvironment-variablesjq

提问by Qirohchan

If I have a JSON like this,

如果我有这样的 JSON,

{
    "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, world1should be printed and similarly for other key-value pairs? Note: The above JSON is present in a variable called $valuesand not in a file.

我想将这些键值对中的每一个导出为环境变量,如何通过 shell 脚本来实现?例如,当我在终端上书写时,echo $hello1,world1应该被打印出来,对于其他键值对也是如此?注意:上面的 JSON 存在于一个被调用的变量中,$values而不是一个文件中。

I know it will be done via jqand written a shell script for this, but it doesn't work.

我知道这将通过jq并为此编写一个 shell 脚本来完成,但它不起作用。

for row in $(echo "${values}" | jq -r '.[]'); do
    -jq() {
        echo ${row} | jq -r 
    }
    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

采纳答案by Turn

Borrowing from this answerwhich 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 jqoutput and exporting them:

借用这个答案,它完成了将 JSON 转换为键=值对的所有艰苦工作,您可以通过循环jq输出并将export它们放入环境中:

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

回答by sjsam

Using command substitution $():

使用命令替换$()

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

Edit :Responding to thiscomment

编辑:回应评论

You should do

你应该做

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

Just mind the doublequotes around $values

请注意double周围的引号$values

Note:Couldn't confirm if there is security implication to this approach, that is if the user could manipulate the jsonto wreak havoc.

注意:无法确认这种方法是否存在安全隐患,即用户是否可以操纵json来造成严重破坏。

回答by Noam Manos

Another way, without using jq, is to parse the json with grep & sed:

另一种不使用jq 的方法是使用grep & sed解析json :

for keyval in $(grep -E '": [^\{]' my.json | sed -e 's/: /=/' -e "s/\(\,\)$//"); do
    echo "export $keyval"
    eval export $keyval
done

Explanation:

解释:

  • First, grep will filter all "key" : valuepairs (value can be "string", number, or boolean).
  • Then, sed will replace :with =, and remove trailing ,.
  • Lastly, exporting the "key"=valuewith eval
  • 首先,grep 将过滤所有"key" : value对(值可以是 "string"numberboolean)。
  • 然后, sed 将替换:=,并删除尾随的,
  • 最后,"key"=value用 eval导出

Here's an output example, exporting json keys, from an AWS record-set:

这是一个输出示例,从 AWS 记录集中导出 json 密钥:

export "Name"="\052.apps.nmanos-cluster-a.devcluster.openshift.com."

export "Type"="A"

export "HostedZoneId"="Z67SXBLZRQ7X7T"

export "DNSName"="a24070461d50270e-1391692.us-east-1.elb.amazonaws.com."

export "EvaluateTargetHealth"=false

导出“名称”="\052.apps.nmanos-cluster-a.devcluster.openshift.com。"

导出“类型”=“A”

导出“HostedZoneId”=“Z67SXBLZRQ7X7T”

导出“DNSName”="a24070461d50270e-1391692.us-east-1.elb.amazonaws.com。"

导出“EvaluateTargetHealth”=false

回答by peak

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

以下 shell 脚本说明的方法避免了大多数(但不是全部)特殊字符问题:

#!/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.

请注意,以上假设键本身没有选项卡。