如何解决Python访问JSON时报TypeError: list indices must be integers or slices, not str
报错原因
你写的取值顺序错误:j['features']对应的是列表(JSON结构中用方括号包裹的集合),必须先用整数索引取出列表内的元素,才能继续取后续的字典属性。你直接对列表用['properties']字符串索引,就触发了TypeError: list indices must be integers or slices, not str报错。
正确取值方式
仅取第一个feature内的字段
直接用[0]取features列表的首个元素,再逐层取属性:
# 取country_code country_code = j['features'][0]['properties']['country_code'] # 取country country = j['features'][0]['properties']['country']
遍历所有feature取值
如果features列表内可能包含多个元素,用循环遍历取值:
for feature in j['features']: current_country_code = feature['properties']['country_code'] current_country = feature['properties']['country'] # 此处添加你的业务处理逻辑
内容的提问来源于stack exchange,提问作者Niloofar
相关产品推荐
相关产品推荐

