Donnie Darko
Donnie Darko

Reputation: 519

JQ filter specific item based on inner item

Having the following Array

[
  [
    { "field" : { "name": "appname" }, "value": { "value" : "app1" } },
    { "field" : { "name": "appstat" }, "value": { "value" : "UP"   } }
  ],
  [
    { "field" : { "name": "appname" }, "value": { "value" : "app2" } },
    { "field" : { "name": "appstat" }, "value": { "value" : "DOWN" } }
  ],
  [
    { "field" : { "name": "appname" }, "value": { "value" : "app3" } },
    { "field" : { "name": "appstat" }, "value": { "value" : "READY"} }
  ]
]

I want to be able to select on specific items based on the appname.

So i can do for example

jq .[] app3

response should be READY

Upvotes: 0

Views: 38

Answers (1)

pmf
pmf

Reputation: 36151

This should bring you there

jq -r --arg q "app3" '
  .[]
  | select(.[] | .field.name == "appname" and .value.value == $q)
  | .[]
  | select(.field.name == "appstat").value.value
'
READY

Demo


However, your data structure seems rather complicated. You'd be better off (at least for this use case) with a simpler array of objects to lookup key-value pairs. For example, transform your input like so:

jq 'map(map({(first(.field.name)): first(.value.value)}) | add)'
[
  {
    "appname": "app1",
    "appstat": "UP"
  },
  {
    "appname": "app2",
    "appstat": "DOWN"
  },
  {
    "appname": "app3",
    "appstat": "READY"
  }
]

Demo

That way, your lookup would be as simple as

jq -r --arg q "app3" '.[] | select(.appname == $q).appstat'
READY

Demo

Upvotes: 1

Related Questions