You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 17:45:05