Guru Guru - 5 months ago 13
JSON Question

access nested data in json

I want to retrieve all the IP address range from Azure cloud from here
The data after conversion in json is in the following format:

{
"AzurePublicIpAddresses": {
"Region": [
{
...
"IpRange": [
{
"_Subnet": "40.69.96.0/19"
},
{
"_Subnet": "40.86.192.0/18"
}
],
"_Name": "canadaeast"
},
{
"IpRange": [
{
"_Subnet": "13.71.160.0/19"
},
{
"_Subnet": "13.88.224.0/19"
},
{
"_Subnet": "40.85.192.0/18"
}
],
"_Name": "canadacentral"
}
],
"_xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
"_xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance"
}
}


I am unable to access IP ranges? through this code?

with open('AZURE_IP.json') as data_file:
data = json.load(data_file)

list_IPCIDR = []
for i in data["AzurePublicIpAddresses"]:
for ii in i["Region"]:
for j in ii["IpRange"]:
list_IPCIDR.append(i["_Subnet"])

sys.stdout=open("test2.txt","w")

Answer

data["AzurePublicIpAddresses"] is a dict. Iterating directly over a dict just gives you the the keys of that dict.

So

for i in data["AzurePublicIpAddresses"]:
    print(i)

will print

Region
_xmlns:xsd
_xmlns:xsi

in some order.

You can get the Subnet IP ranges like this:

list_IPCIDR = []
for ipr in data["AzurePublicIpAddresses"]["Region"]:
    for d in ipr["IpRange"]:
        list_IPCIDR.append(d["_Subnet"])

print(list_IPCIDR)

output

['40.69.96.0/19', '40.86.192.0/18', '13.71.160.0/19', '13.88.224.0/19', '40.85.192.0/18']

This works because data["AzurePublicIpAddresses"]["Region"] is a list of dicts. Each of those dict (that are temporarily bound to the name ipr) contains a list of dicts associated with the "IpRange" key, so we need to iterate over those lists in the inner loop, and then extract the subnet strings from those inner dicts.

If you like you can do this in a list comprehension, butI advise splitting it up over several lines, eg:

list_IPCIDR = [d["_Subnet"] 
    for ipr in data["AzurePublicIpAddresses"]["Region"] 
        for d in ipr["IpRange"]]
Comments