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

复杂嵌套JSON元素访问:循环时报string indices must be integers错误如何解决

问题原因

data['json']['response']['widgets']['carbonwidget/single-1']['dataDetails'] 是字典结构而非列表,你直接对字典执行for ... in遍历时,迭代返回的是字典的键(也就是示例中的字符串'558725'),而非键对应的字典值。你尝试对字符串类型的键执行['podContent']类字典索引操作,自然会触发string indices must be integers报错。

修复方案

可以选择以下任意一种方式修改遍历逻辑,额外增加的长度判断是为了避免部分节点podContent长度不足时触发索引越界,稳定性更好:

方式1:遍历同时取键值对

data_details = data['json']['response']['widgets']['carbonwidget/single-1']['dataDetails']
for data_detail_key, data_detail_val in data_details.items():
    if len(data_detail_val.get('podContent', [])) >= 4:
        print(data_detail_val['podContent'][3]['data']['html'])

方式2:用遍历得到的键取对应值

data_details = data['json']['response']['widgets']['carbonwidget/single-1']['dataDetails']
for data_detail_no in data_details:
    data_detail_val = data_details[data_detail_no]
    if len(data_detail_val.get('podContent', [])) >= 4:
        print(data_detail_val['podContent'][3]['data']['html'])

内容的提问来源于stack exchange,提问作者motorleague

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 02:18:01