我正在尝试学习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”`。有没有其他方法可以解析这个长列表来提取“地名”、“州”等。?在
提前谢谢!在
引用这个答案:https://stackoverflow.com/a/3294899/3474873
如果您使用的是python3.x,请看一下实际的答案,因为有一些细微的差别。在
现在在你的情况下。首先,
api_return
中没有名为"place"
的密钥。即使你做得对,你还是会出错。在如果需要访问所有数据,则最简单的方法是在for循环中包含If语句,以检查所有键,如下所示:
如果只需要一个值,则可以跳过for循环,只需运行:
^{pr2}$显示的两个代码段都将返回
api_return['places']
中包含的内部数组,并将其存储在places
中,places[0]
是另一个字典,可以像上面一样进行研究。在编辑: 为了避免混淆,您还需要使用
json
解析接收到的字符串,就像下面所示的mightyKeyboard。在相关问题 更多 >
编程相关推荐