Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

jq .[] app3

response should be READY

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading