简体   繁体   中英

JQ - how to display objects based on on the value of objects in an array

I have a JSON file that looks like this:

{
  "InstanceId": "i-9KwoRGF6jbhYdZi823aE4qN",
  "Tags": [
    {
      "Key": "blah",
      "Value": "server-blah"
    },
    {
      "Key": "environment",
      "Value": "ops"
    },
    {
      "Key": "server_role",
      "Value": "appserver"
    },
    {
      "Key": "Name",
      "Value": "some_name"
    },
    {
      "Key": "product",
      "Value": "some_server"
    }
  ]
}
{
   ...more objects like the above...
}

I need to display the InstanceId where "Key" == "environment" and "Value" == "ops". I have jq-1.6.

If I say:

cat source.json | jq '
   { InstanceId, Tags } |
   (.Tags[] | select( .Key == "environment" ))
'

I get some of what I want, but I cannot figure out how to include InstanceId in the output nor how to incorporate the "and" part of the select.

Here is a simple but efficient approach using any :

select( any(.Tags[]; .Key=="environment" and .Value == "ops") )
| .InstanceId

An alternative approach that avoids .Tags[] :

{"Key": "environment", "Value": "ops"} as $object
| select( .Tags | index($object) )
| .InstanceId

I'm not sure if this is the exact output you're looking for (comment if it isn't), but this will output the InstanceId s of JSON objects that contain a Tag with Key environment and Value ops .

jq 'select( .Tags[] | (.Key == "environment" and .Value == "ops")) | .InstanceId' < source.json

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