0

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 Ainformation, the nestedNS` 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!

Jishan
  • 1,654
  • 4
  • 28
  • 62
  • Something like what's in [this answer](https://stackoverflow.com/a/14059645/355230) of mine could be adapted to do this (I think). – martineau Nov 30 '17 at 00:27
  • @martineau I had been there as well as https://stackoverflow.com/questions/14547916/how-can-i-loop-over-entries-in-json, but still could not figure out. This is my first time working with both python and json in python. – Jishan Nov 30 '17 at 00:35

2 Answers2

1

You can do something like this:

def get_values(data, scope=None):
    for entry in data:
        for prop, value in entry.items():
            if scope is not None and prop != scope:
                continue
            if not isinstance(value, list):
                yield value
            else:
                for elem in value:
                    yield elem

And then:

for value in get_values(data):
    print(value)

You can also:

for value in get_values(data, scope="NS"):
    print(value)
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
1

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.

Blckknght
  • 100,903
  • 11
  • 120
  • 169