2014-04-26 118 views
23

我想使用zippopotam.us獲取特定城市的郵政編碼。我有以下的代碼工作,除非我嘗試訪問post code鍵返回TypeError: expected string or bufferPython訪問嵌套的JSON數據

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

data = json.loads(j) 

print j['state'] 
print data['places']['latitude'] 

完整的JSON輸出:

{ 
"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" 
} 

感謝您的幫助。

回答

13

我沒有意識到第一個嵌套元素實際上是一個數組。訪問郵政編碼密鑰的正確方法如下:

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

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

位置是一個列表而不是字典。因此,下面的這一行不應該起作用:

print data['places']['latitude'] 

您需要選擇位置中的某個項目,然後才能列出該位置的屬性。因此,要獲得後的第一個代碼,你會怎麼做:

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

在代碼中j是已經JSON數據和j [「地方」]是列表中未字典。

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

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

我使用這個LIB訪問嵌套的字典鍵

https://github.com/mewwts/addict

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

print j.state 
print j.places[1]['post code'] # only work with keys without '-', space, or starting with number