
本文详解如何在python中准确访问含多层嵌套与列表结构的json数据,重点解决因误将列表当作字典访问而导致的typeerror,并提供健壮、可复用的提取方案。
本文详解如何在python中准确访问含多层嵌套与列表结构的json数据,重点解决因误将列表当作字典访问而导致的typeerror,并提供健壮、可复用的提取方案。
从错误信息 TypeError: list indices must be integers, not str 可以明确看出问题根源:代码试图用字符串键 "generationmix" 直接索引一个列表(而非字典),而Python中列表只能通过整数下标访问。
观察原始JSON结构:
{
"data": [
{
"dnoregion": "England",
"data": [
{
"generationmix": [
{"fuel": "biomass", "perc": 8.8},
{"fuel": "coal", "perc": 0},
{"fuel": "imports", "perc": 10.3},
...
]
}
]
}
]
}可见 "data" 是长度为1的列表,其首个元素([0])是一个字典;该字典内又有一个 "data" 字段,同样为列表,需再次取 [0];最终 "generationmix" 本身也是一个燃料项列表,必须遍历才能定位 "coal"。
exa-js 是 Exa 官方 JavaScript 软件开发工具包,Exa 是一个为 AI 工作流构建的网络搜索 API。它为代理提供了一种具体的方式来搜索网络、检索页面内容,并从代码中生成有来源的答案,而不是手动拼接原始 HTTP 调用。
✅ 正确做法是逐层解构并安全遍历:
import requests
import json
response = requests.get(grid_url)
grid_data = response.json() # 推荐直接使用 .json(),比 json.loads(response.text) 更简洁安全
# 安全路径访问(带存在性检查)
try:
# 提取 generationmix 列表
generation_mix = (
grid_data.get("data", [{}])[0]
.get("data", [{}])[0]
.get("generationmix", [])
)
# 查找 coal 条目
coal_entry = next((item for item in generation_mix if item.get("fuel") == "coal"), None)
if coal_entry:
coal_percentage = coal_entry.get("perc", 0)
print(f"coal percentage: {coal_percentage}%")
else:
print("Warning: 'coal' fuel entry not found in generation mix.")
except (KeyError, IndexError, TypeError) as e:
print(f"Data structure error: {e}")? 关键要点总结:
- 永远先确认数据类型:用 type(obj) 或 isinstance(obj, list/dict) 快速验证;
- 避免硬编码索引:对可能为空或结构变化的API响应,优先使用 .get() 和默认值;
- 遍历优于硬索引:当目标字段位于列表中(如 fuel 类型数组),用 next() + 生成器表达式更清晰、安全;
- 异常处理必不可少:真实API响应可能缺失字段、格式变更或返回错误体,健壮代码应覆盖常见失败场景。
这样不仅解决了当前的 coal 提取问题,也为后续扩展(如提取 wind、nuclear 或计算总和)打下可维护基础。

















