[英]bash use jq to get value if condition meets
I am trying to get certain value in the json with some for each and if condition.我试图在 json 中获得一定的价值,每个条件都有一些。
code looks like the following代码如下所示
for i in "$(jq -r '.value[]' test.json)"; do
result=$(echo $i | jq -r .result)
if [ "$result" == "succeeded" ]
then
name=$(echo $i | jq -r .agent.name)
echo "$name"
fi
done
json file - test.json json 文件 - test.json
{
"count":3,
"value":[
{
"location":"CA",
"result":"failed",
"agent":{
"id":97833,
"name":"Brad"
},
"priority":0
},
{
"location":"TX",
"result":"failed",
"agent":{i
"id":15232,
"name":"Tom"
},
"priority":0
},
{
"location":"CO",
"result":"succeeded",
"agent":{
"id":13412,
"name":"John"
},
"priority":0
}
]
}
I am trying to loop through the json file using jq to get the name of the agent if the result was "succeeded".如果结果“成功”,我正在尝试使用 jq 遍历 json 文件以获取代理的名称。 but the result i get from result=$(echo $i | jq -r.result) seems like it's returning string array @("failed","failed","succeeded").
但是我从 result=$(echo $i | jq -r.result) 得到的结果似乎是返回字符串数组@("failed","failed","succeeded")。
========================update============================== =========================更新========================= =====
jq ' # get the name of the agent if the result was "succeeded".
.value[]
| select(.result == "succeeded")
| var1=.agent.name
| echo $var1
' test.json
if I want to save the.agent.name into a variable and use it with a different command, what do I have to do?如果我想将.agent.name 保存到一个变量中并与不同的命令一起使用,我该怎么办?
There is no need to use a shell loop.无需使用 shell 回路。
With your test.json,用你的test.json,
jq ' # get the name of the agent if the result was "succeeded".
.value[]
| select(.result == "succeeded")
| .agent.name
' test.json
produces:产生:
"John"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.