Jeet.Deir Jeet.Deir - 9 months ago 81
JSON Question

Looping over Nested JSON Elements

So I have a JSON that looks like this:

[
{
"Domain": "apple.com",
"A": [
"17.142.160.59",
"17.172.224.47",
"17.178.96.59"
],
"NS": [
"c.ns.apple.com.",
"b.ns.apple.com.",
"a.ns.apple.com.",
"f.ns.apple.com.",
"nserver5.apple.com.",
"nserver6.apple.com.",
"d.ns.apple.com.",
"e.ns.apple.com."
]
}
]


While I can retrieve the nested information manually like viz.

print(data[0]["Domain"]) --- Returns: apple.com
print(data[0]["A"][0]) --- Returns: 17.142.160.59


How can I loop through the information that let me retrieve the Domain, the the nested A
information, the nested
NS` information etc.?

I tried doing this:

for i in data["Domain"]:
print(data[i]["Domain"])
for j in ... // could not figure out, either way first loop fails.


in vain. Thanks for any help!

Answer Source

Your data value coming from JSON is a going to be list, so you can iterate over the dictionaries it contains with a for loop:

for inner in data:

Then you can just use inner['Domain'] or inner['A'] to access the values associated with the keys you want. To iterate over the A records, use another loop on inner['A'].

Here's a set of nested loops that I think does what you want:

for inner in data:
    print("Domain:", inner['Domain'])
    for ip in inner['A']:
        print(" IP:", ip)
    for ns in inner['NS']:
        print(" NS:", ns)

You can of course do something else with the data, rather than printing it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download