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" }
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.
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.
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.
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With