如果条件满足,bash使用jq获取值

won*_*ity 1 bash select json jq

我试图在 json 中获取某些值,其中每个值和 if 条件都有一些值。

代码如下所示

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
Run Code Online (Sandbox Code Playgroud)

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
      }
   ]
}
Run Code Online (Sandbox Code Playgroud)

如果结果“成功”,我尝试使用 jq 循环遍历 json 文件以获取代理的名称。但我从 result=$(echo $i | jq -r .result) 得到的结果似乎返回字符串数组 @("failed","failed","succeeded")。

=======================更新========================== =====

jq ' # get the name of the agent if the result was "succeeded".
  .value[]
  | select(.result == "succeeded")
  | var1=.agent.name
  | echo $var1
' test.json
Run Code Online (Sandbox Code Playgroud)

如果我想将 .agent.name 保存到变量中并在不同的命令中使用它,我该怎么办?

pea*_*eak 7

无需使用 shell 循环。

使用你的 test.json,

jq ' # get the name of the agent if the result was "succeeded".
  .value[]
  | select(.result == "succeeded")
  | .agent.name
' test.json

Run Code Online (Sandbox Code Playgroud)

产生:

"John"
Run Code Online (Sandbox Code Playgroud)

  • 要获得不带双引号的输出,请将“-r”标志添加到“jq”。注意:不要尝试使用“for”循环迭代结果 - 请参阅 [BashFAQ #1:“如何逐行(和/或字段)读取文件(数据流、变量)”按字段)?"](https://mywiki.wooledge.org/BashFAQ/001) (2认同)