简体   繁体   中英

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.

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

{
   "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". but the result i get from result=$(echo $i | jq -r.result) seems like it's returning string array @("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?

There is no need to use a shell loop.

With your test.json,

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

produces:

"John"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM