Python iterate Json with different attribute names

0

Good morning, I'm working with the Cisco Meraki API, my problem is that I need to iterate and save the data that comes from a json like the following:

    [
  {
    "name":"My AP",
    "lat":37.4180951010362,
    "lng":-122.098531723022,
    "serial":"Q2XX-XXXX-XXXX",
    "mac":"00:11:22:33:44:55:66",
    "model":"MR34",
    "address":"1600 Pennsylvania Ave",
    "lanIp":"1.2.3.4"
    "tags":" recently-added ",
    "networkId":"N_1234",
    "beaconIdParams": {
      "uuid": "00000000-0000-0000-0000-000000000000",
      "major": 5,
      "minor": 3,
    }
  }
]

I can easily obtain data like networkId when iterating the data in the following way:

for each in api_data:
        print(each["networkId"])}

but the problem is that attributes like beaconIdParams and lanIp do not appear in all the fixes or appear with other names (for example lanIp can change to wan1Ip or in some cases beaconIdParams does not appear) so I would like to know how to put conditions so that you can return the values of those attributes to me. I hope I can receive your help, Thanks.

    
asked by zentx11 08.03.2018 в 23:06
source

1 answer

0

You can try the following:

for each in api_data:
    beaconIdParams = each.get('beaconIdParams', None)

Assuming you iterate over a list of dictionaries; the get method allows you to avoid a "KeyError", defining a default value, in this example the default value would be None.

    
answered by 08.03.2018 в 23:35