我正在尝试使用 zippopotam.us 获取特定城市的邮政编码。我有以下代码有效,除非我尝试访问 post code
键返回 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']
完整的 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"
}
原文由 apardes 发布,翻译遵循 CC BY-SA 4.0 许可协议
我没有意识到第一个嵌套元素实际上是一个数组。获取post code key的正确方法如下: