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

提取JSON字段触发TypeError: string indices must be integers如何解决

报错根源

TypeError: string indices must be integers 由错误的链式字段取值逻辑导致:
原代码中data['archive'][0]['service_name']['date']['summary']的取值路径,是在拿到service_name对应的字符串值后,继续尝试用字符串keydate访问该字符串的内部属性。Python中字符串仅支持整数下标取值,用字符串做索引直接触发类型错误。
对照接口返回的JSON结构,service_name、summary、date是archive[0]对象下的三个平级字段,不存在逐层嵌套的从属关系,不能串成链式路径取值。

正确实现代码

先定位到目标对象archive[0],再单独提取三个平级字段,组装后序列化传入模板即可:

# 定位目标归档对象
target_item = data['archive'][0]
# 提取指定的三个字段
result = {
    "service_name": target_item["service_name"],
    "summary": target_item["summary"],
    "date": target_item["date"]
}
# 渲染模板
return render_template('index.html', data=json.dumps(result))
注意事项
  • 取值前可先加判断校验archive数组长度,避免数组为空时触发索引越界错误
  • 若接口返回的原始数据是JSON字符串,需要先通过json.loads()转成Python字典再做字段提取,不要直接对字符串做key索引操作

内容的提问来源于stack exchange,提问作者Carolina D Vallecillo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 21:27:20