Eric Graham
Eric Graham

Reputation: 21

Python to parse nested JSON values that can be null sometimes

I'm trying to parse the following and pull out primary_ip as a variable. Sometimes primary_ip is "null". Here is an example of the JSON, code and the most recent error I am getting.

{
  "count": 67,
  "next": "https://master.netbox.dev/api/dcim/devices/?limit=50&offset=50",
  "previous": null,
  "results": [
   {
      "id": 28,
      "url": "https://master.netbox.dev/api/dcim/devices/28/",
      "name": "q2",
      "display_name": "q2",
      "device_type": {
        "id": 20,
        "url": "https://master.netbox.dev/api/dcim/device-types/20/",
        "manufacturer": {
          "id": 15,
          "url": "https://master.netbox.dev/api/dcim/manufacturers/15/",
          "name": "Zyxel",
          "slug": "zyxel"
        },
        "model": "GS1900",
        "slug": "gs1900",
        "display_name": "Zyxel GS1900"
      },
      "device_role": {
        "id": 4,
        "url": "https://master.netbox.dev/api/dcim/device-roles/4/",
        "name": "Access Switch",
        "slug": "access-switch"
      },
      "primary_ip": {
        "id": 301,
        "url": "https://master.netbox.dev/api/ipam/ip-addresses/301/",
        "family": 4,
        "address": "172.31.254.241/24"
      },

Example Python

import requests
import json

headers = {
    'Authorization': 'Token 63d421a5f733dd2c5070083e80df8b4d466ae525',
    'Accept': 'application/json; indent=4',
}

response = requests.get('https://master.netbox.dev/api/dcim/sites/', headers=headers)
j = response.json()

for results in j['results']:
    x=results.get('name')
    y=results.get('physical_address')

response2 = requests.get('https://master.netbox.dev/api/dcim/devices', headers=headers)
device = response2.json()
for result in device['results']:
  x=result.get('name')
  z=result.get('site')['name']
#  if result.get('primary_ip') != None
  y=result.get('primary_ip', {}).get('address')

  print(x,y,z)

I get the following error when I run it:

ubuntu@ip-172-31-39-26:~$ python3 Netbox-python

  Traceback (most recent call last):
      File "Netbox-python", line 22, in <module>
        y=result.get('primary_ip', {}).get('address')
    AttributeError: 'NoneType' object has no attribute 'get'

Upvotes: 0

Views: 608

Answers (1)

mrpbennett
mrpbennett

Reputation: 1956

Which value is None? Is it the primary_ip or is it address ?

you could try the following:

y = result.get('primary_ip', {}).get('address, 'empty_address')

This will replace any None values with empty_address


Update:

I have just ran your code and got the following output:

LC1 123.123.123.123/24 site1
q1 172.31.254.254/24 COD
q2 172.31.254.241/24 COD

After running this:

import requests
import json

headers = {
    "Authorization": "Token 63d421a5f733dd2c5070083e80df8b4d466ae525",
    "Accept": "application/json; indent=4",
}

response = requests.get("https://master.netbox.dev/api/dcim/sites/", headers=headers)
j = response.json()

for results in j["results"]:
    x = results.get("name")
    y = results.get("physical_address")

response2 = requests.get("https://master.netbox.dev/api/dcim/devices", headers=headers)
device = response2.json()

for result in device["results"]:
    x = result.get("name")
    z = result.get("site")["name"]

    if result.get("primary_ip") != None:
        y = result.get("primary_ip").get("address")

        print(x, y, z)

I am not sure of the expected output but the code doesn't throw any errors. From looking at the code, it seems there were a few indentation errors, where things didn't match up in terms of where they should have been indented.

Upvotes: 2

Related Questions