Skip to content Skip to sidebar Skip to footer

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

Solution 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.


Solution 2:

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)

Post a Comment for "Looping Over Nested JSON Elements"