[英]jq extract value of keypair and assign to bash variable
jq does my head in sometimes. jq有时会引起我的注意。 Assume you have a json file called
emails.json
that looks like this; 假设您有一个名为
emails.json
的json文件,看起来像这样;
[
{
"ParameterKey": "foo1",
"ParameterValue": "bar1"
},
{
"ParameterKey": "foo2",
"ParameterValue": "bar2"
}
]
If I run my bash script (let's call it script.sh
) using the argument foo1, I want to have bar1 assigned to a variable called emailAdd
. 如果我使用参数foo1运行bash脚本(我们称其为
script.sh
),我希望将bar1分配给名为emailAdd
的变量。 Likewise, if I use the argument foo2, I want bar2 assigned. 同样,如果我使用参数foo2,则希望分配bar2。
I thought my script would look like the following, but I'm getting an empty variable. 我以为我的脚本如下所示,但是我得到了一个空变量。
#!/usr/bin/env bash
EMAIL=$1
emailAdd=$(jq --arg email "$EMAIL" '.[] | select(.ParameterKey=="$email") | .ParameterValue' < emails.json)
echo "address is " $emailAdd
So, running sh script.sh foo1
I would expect address is bar1
, etc 因此,运行
sh script.sh foo1
我希望address is bar1
,等等
You pretty much have it correct. 您几乎正确了。 You don't need the quotes around
$email
, because unlike shell, jq
actually treats that as a variable containing a value, rather than something to expand to arbitrary text. 您不需要
$email
周围的引号,因为与shell不同, jq
实际上将其视为包含值的变量,而不是扩展为任意文本的变量。 You probably also want to use the -r
option so that the output is bar1
, rather than "bar1"
. 您可能还希望使用
-r
选项,以便输出为bar1
而不是"bar1"
。
#!/usr/bin/env bash
EMAIL=$1
emailAdd=$(jq -r --arg email "$EMAIL" '.[] | select(.ParameterKey==$email) | .ParameterValue' < emails.json)
echo "address is $emailAdd"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.