jq: how to select object based on key value

Modified on Thu, 25 May, 2023 at 12:36 PM

Suppose we have the following data structure, and we want to select on the public IPv4 address only:


{
   "ip_addresses":[
      {
         "address":"145.40.82.9",
         "address_family":4,
         "cidr":31,
         "gateway":"145.40.82.8",
         "netmask":"255.255.255.254",
         "network":"145.40.82.8",
         "public":true
      },
      {
         "address":"2604:1380:45e1:c100::1",
         "address_family":6,
         "cidr":127,
         "gateway":"2604:1380:45e1:c100::",
         "netmask":"ffff:ffff:ffff:ffff:ffff:ffff:ffff:fffe",
         "network":"2604:1380:45e1:c100::",
         "public":true
      },
      {
         "address":"10.67.3.1",
         "address_family":4,
         "cidr":31,
         "gateway":"10.67.3.0",
         "netmask":"255.255.255.254",
         "network":"10.67.3.0",
         "public":false
      }
   ]
}

In the example above, the following jq command can be used:

'jq( [.ip_addresses[] | select(.address_family==4)] | .[] | select(.public) )'

The breakdown for the jq command is as follow:

[.ip_addresses[] | select(.address_family==4)]

... selects the array of ip_addresses and uses the first select statement to create an array of IPv4 addresses (the array is necessary in case there are more than one).

| .[] | select(.public)

... takes the object created in the previous step and passes it to another select statement, in this case where public==true

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article