解析restapi结果python

2024-09-27 09:27:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试学习API,我有一个对http://api.zippopotam.us/us/90210的调用,结果是:

{"post code": "90210", "country": "United States", "country abbreviation": "US", "places": [{"place name": "Beverly Hills", "longitude": "-118.4065", "state": "California", "state abbreviation": "CA", "latitude": "34.0901"}]}

API使用国家(美国)和邮政编码返回“place”。我试图将“place”段解析为如下变量:

^{pr2}$

但是,我收到一条错误消息:“TypeError:String index must be integers”`。有没有其他方法可以解析这个长列表来提取“地名”、“州”等。?在

提前谢谢!在


Tags: apihttpcodeplacepostcountryunitedus
2条回答
import json

data_str = '{"post code": "90210", "country": "United States", "country abbreviation": "US", "places": [{"place name": "Beverly Hills", "longitude": "-118.4065", "state": "California", "state abbreviation": "CA", "latitude": "34.0901"}]}'

data_json = json.loads(data_str)

for item in data_json['places']:
    print item['place name']

#you can access the 'places' key-vals via the following, but
#it's not that pretty
print data_str['places'][0]['place name']

引用这个答案:https://stackoverflow.com/a/3294899/3474873

for key in d: will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following:

for key, value in d.iteritems():

如果您使用的是python3.x,请看一下实际的答案,因为有一些细微的差别。在

现在在你的情况下。首先,api_return中没有名为"place"的密钥。即使你做得对,你还是会出错。在

如果需要访问所有数据,则最简单的方法是在for循环中包含If语句,以检查所有键,如下所示:

for key, value in d.iteritems():
    if (key == "places"):
        places = value
    elif ...

如果只需要一个值,则可以跳过for循环,只需运行:

^{pr2}$

显示的两个代码段都将返回api_return['places']中包含的内部数组,并将其存储在places中,places[0]是另一个字典,可以像上面一样进行研究。在

编辑: 为了避免混淆,您还需要使用json解析接收到的字符串,就像下面所示的mightyKeyboard。在

相关问题 更多 >

    热门问题