Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Accessing Nested JSON Data [duplicate]

Tags:

python

json

I'm trying to get the zip code for a particular city using zippopotam.us. I have the following code which works, except when I try to access the post code key which returns TypeError: expected string or buffer

r = requests.get('http://api.zippopotam.us/us/ma/belmont') j = r.json()  data = json.loads(j)  print j['state'] print data['places']['latitude'] 

Full JSON output:

{ "country abbreviation": "US", "places": [     {         "place name": "Belmont",         "longitude": "-71.4594",         "post code": "02178",         "latitude": "42.4464"     },     {         "place name": "Belmont",         "longitude": "-71.2044",         "post code": "02478",         "latitude": "42.4128"     } ], "country": "United States", "place name": "Belmont", "state": "Massachusetts", "state abbreviation": "MA" } 
like image 454
apardes Avatar asked Apr 26 '14 04:04

apardes


People also ask

How do I get nested JSON data in Python?

Use pd. read_json() to load simple JSONs and pd. json_normalize() to load nested JSONs. You can easily access values in your JSON file by chaining together the key names and/or indices.

Can JSON have duplicate keys Python?

You cannot have duplicate key in a dictionary. Duplicate keys in JSON aren't covered by the spec and can lead to undefined behavior (see this question). If you read the JSON into a Python dict, the information will be lost, since Python dict keys must be unique.

How do you access JSON elements in Python?

It's pretty easy to load a JSON object in Python. Python has a built-in package called json, which can be used to work with JSON data. It's done by using the JSON module, which provides us with a lot of methods which among loads() and load() methods are gonna help us to read the JSON file.

How do you flatten a JSON in Python?

There are many ways to flatten JSON. There is one recursive way and another by using the json-flatten library. Now we can flatten the dictionary array by a recursive approach which is quite easy to understand. The recursive approach is a bit slower than using the json-flatten library.


1 Answers

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 place's properties. So to get the first post code you'd do:

print data['places'][0]['post code'] 
like image 175
agrinh Avatar answered Sep 21 '22 17:09

agrinh