Python Accessing Nested JSON Data

Python Accessing Nested JSON Data

Places is a list and not a dictionary. This line below should therefore not work:

print data[places][latitude]

You need to select one of the items in places and then you can list the places properties. So to get the first post code youd do:

print data[places][0][post code]

I did not realize that the first nested element is actually an array. The correct way access to the post code key is as follows:

r = requests.get(http://api.zippopotam.us/us/ma/belmont)
j = r.json()

print j[state]
print j[places][1][post code]

Python Accessing Nested JSON Data

In your code j is Already json data and j[places] is list not dict.

 r = requests.get(http://api.zippopotam.us/us/ma/belmont)
 j = r.json()

 print j[state]
 for each in j[places]:
    print each[latitude]

Leave a Reply

Your email address will not be published. Required fields are marked *