我正在尝试使用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']
Run Code Online (Sandbox Code Playgroud)
完整的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"
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助.
agr*_*inh 61
地方是一个列表而不是字典.因此,以下这一行不适用:
print data['places']['latitude']
Run Code Online (Sandbox Code Playgroud)
您需要选择其中一个项目,然后您可以列出该地点的属性.所以要获得你要做的第一个帖子代码:
print data['places'][0]['post code']
Run Code Online (Sandbox Code Playgroud)
apa*_*des 24
我没有意识到第一个嵌套元素实际上是一个数组.访问邮政编码密钥的正确方法如下:
r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()
print j['state']
print j['places'][1]['post code']
Run Code Online (Sandbox Code Playgroud)
在你的代码中,j是已经是json数据而j ['places']是list而不是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']
Run Code Online (Sandbox Code Playgroud)
小智 5
我正在使用此lib来访问嵌套的dict键
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
Run Code Online (Sandbox Code Playgroud)