Nested Selection Criteria in jq

I’m working with API data from a netbox instance. I want to select a device-typ URL based on the manufacturer. However, the value “manufacturer” in the result is a dictionary. I want to select where that manufacturer has the name “Ampere” or some other manufacturer.

To get the data, I run curl:

curl -H "Authorization: Token $TOKEN" -s http://$NETBOX_HOST/api/dcim/device-types/

Which gives me many records. How many?

curl -H "Authorization: Token $TOKEN" -s http://$NETBOX_HOST/api/dcim/device-types/ | jq '.results | length ' 
4

If I look at the first record,

curl -H "Authorization: Token $TOKEN" -s http://$NETBOX_HOST/api/dcim/device-types/ | jq '.results | .[0] '

I can see the manufacturer dictionary:

{
  "id": 3,
  "url": "http://10.76.117.67:8000/api/dcim/device-types/3/",
  "display": "falcon",
  "manufacturer": {
    "id": 1,
    "url": "http://10.76.117.67:8000/api/dcim/manufacturers/1/",
    "display": "Ampere",
    "name": "Ampere",
    "slug": "ampere"
  },
  "model": "falcon",
  "slug": "falcon",
  "part_number": "",
  "u_height": 2,
  "is_full_depth": true,
  "subdevice_role": null,
  "airflow": null,
  "front_image": null,
  "rear_image": null,
  "comments": "",
  "tags": [],
  "custom_fields": {},
  "created": "2021-12-10",
  "last_updated": "2021-12-10T01:16:16.231561Z",
  "device_count": 0
}

In order to select all of the records where the manufacturer id is 1, and compose a select filter using dot notation,

and make sure I use == for comparison.

 curl -H "Authorization: Token $TOKEN" -s http://$NETBOX_HOST/api/dcim/device-types/ | jq '.results | .[] | select(.manufacturer.id == 2)' | jq '.'

In this case, it would return 5 records. I want the device-type model, which can be select from the output of the select:

curl -H "Authorization: Token $TOKEN" -s http://$NETBOX_HOST/api/dcim/device-types/ | jq '.results | .[] | select(.manufacturer.id == 1) | .model' 
"falcon"
"jade.mystique"

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.