97

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"
}
Braiam
  • 1
  • 11
  • 47
  • 78
apardes
  • 4,272
  • 7
  • 40
  • 66
  • 1
    Plop your JSON into [the tool in this snippet](https://stackoverflow.com/a/68460317/6243352), check 'brackets only', then click the node you want to copy its code path to the clipboard. – ggorlen Jul 20 '21 at 22:19
  • The original question was essentially the result of a typo, but people who find this question later will be more interested in the linked duplicate. – Karl Knechtel Jul 02 '22 at 01:03

4 Answers4

116

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'])
larsaars
  • 2,065
  • 3
  • 21
  • 32
agrinh
  • 1,835
  • 2
  • 10
  • 11
48

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']
apardes
  • 4,272
  • 7
  • 40
  • 66
14

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']
MONTYHS
  • 926
  • 1
  • 7
  • 30
8

I'm using this lib to access nested dict keys

https://github.com/mewwts/addict

 import requests
 from addict import Dict
 r = requests.get('http://api.zippopotam.us/us/ma/belmont')
 j = Dict(r.json())

 print j.state
 print j.places[1]['post code']  # only work with keys without '-', space, or starting with number 
arielf
  • 5,802
  • 1
  • 36
  • 48
Ezequiel Bertti
  • 810
  • 8
  • 15