Shahriar
Shahriar

Reputation: 13804

How to skip iteration in JQ

{   "items":[
    {
      "metadata":{"name":"127.0.0.1"},
      "status":{
        "capacity":{"cpu":3}
      }
    },
    {
      "metadata":{"name":"127.0.0.2"},
      "status":{
        "capacity":{"cpu":8}
      }
    }   ] }

I want to do following:

.items[] | if .metadata.name=="127.0.0.1" then {cpu: .status.capacity.cpu} else <<I want to skip>> end

I want skip if 1st continue is false

Required Output:

{"cpu":3}

Upvotes: 2

Views: 484

Answers (2)

peak
peak

Reputation: 116957

@aerofile-kite - Your first instinct is right. There is no need to use map and in your case, it is probably more efficient not to use it. Following your line of thought, you could write:

.items[]
| if .metadata.name=="127.0.0.1"
  then {cpu: .status.capacity.cpu}
  else empty
  end

or more succinctly:

  .items[]
  | select(.metadata.name=="127.0.0.1")
  | { cpu: .status.capacity.cpu } 

Upvotes: 3

Fedor Dikarev
Fedor Dikarev

Reputation: 506

Use map(select(...)):

jq '.items|map(select(.metadata.name == "127.0.0.1"))|.[].status.capacity' items 
{
  "cpu": 3
}

Upvotes: 2

Related Questions