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

Python转换JSON格式报TypeError: string indices must be integers如何解决

问题排查与解决

错误根因

  • 索引逻辑错误:metadata[key]['name']取出的是"Orange"、"Apple"这类字符串值,你试图对字符串执行['dir']、['path']的字典式键索引,而字符串仅支持整数下标索引,因此触发TypeError: string indices must be integers报错。
  • 赋值逻辑错误:你需要的最终结构是水果名对应{dir路径: path路径}的字典,但原代码反复覆盖水果名对应的值,无法生成目标结构。

修正代码

import json

fruits = {}
with open('fruits.json', 'r') as data:
    metadata = json.load(data)
    # 遍历直接拿到的value即可,无需重复取metadata[key]
    for _, value in metadata.items():
        fruits[value['name']] = {value['dir']: value['path']}

# 如需写入新文件可添加以下代码
# with open('formatted_fruits.json', 'w') as f:
#     json.dump(fruits, f, indent=4)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:36:05