Subhankar
Subhankar

Reputation: 507

Jq parsing : Selecting an object from a list of objects based on criteria

I have a JSON like this.

{
  "servers": [
    {
      "id": "1",
      "addresses": {
        "services_z1": [
          {
            "OS-EXT-IPS-MAC:mac_addr": "fa:16:3e:bc:db:7d",
            "addr": "10.3.3.18",
            "version": 4,
            "OS-EXT-IPS:type": "fixed"
          }
        ]
      }

    },

    {
      "id": "2",
      "addresses": {
        "services_z1": [
          {
            "OS-EXT-IPS-MAC:mac_addr": "fa:16:3e:bc:db:7d",
            "addr": "10.3.3.19",
            "version": 4,
            "OS-EXT-IPS:type": "fixed"
          }
        ]
      }

    },

    {
      "id": "3",
      "addresses": {
        "services_z1": [
          {
            "OS-EXT-IPS-MAC:mac_addr": "fa:16:3e:bc:db:7d",
            "addr": "10.3.3.20",
            "version": 4,
            "OS-EXT-IPS:type": "fixed"
          }
        ]
      }

    },

    {
      "id": "4",
      "addresses": {
        "services_z1": [
          {
            "OS-EXT-IPS-MAC:mac_addr": "fa:16:3e:bc:db:7d",
            "addr": "10.3.3.21",
            "version": 4,
            "OS-EXT-IPS:type": "fixed"
          }
        ]
      }

    }

    ]

}

I am trying to find the server id for which the addr value is 10.3.3.18. How can I achieve that?

I know that it would be something like jq '.servers[] | select(some criteria)'

But I am not able ot form that criteria.

Any pointer would be of huge help.

Upvotes: 1

Views: 524

Answers (1)

Paul Wagland
Paul Wagland

Reputation: 29134

You want something like the following:

jq '.servers[]|select(.addresses.services_z1[].addr=="10.3.3.18")|.id'

This says to look through all of the servers, match those that have .addresses.services_z1[].addr=="10.3.3.18", and then print the id of those servers.

Upvotes: 4

Related Questions