簡體   English   中英

bash 如果條件滿足,則使用 jq 獲取值

[英]bash use jq to get value if condition meets

我試圖在 json 中獲得一定的價值,每個條件都有一些。

代碼如下所示

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 文件 - 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
      }
   ]
}

如果結果“成功”,我正在嘗試使用 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

如果我想將.agent.name 保存到一個變量中並與不同的命令一起使用,我該怎么辦?

無需使用 shell 回路。

用你的test.json,

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

產生:

"John"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM