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

如何用Python修改JSON文件中列表元素值?解决TypeError报错

解决JSON列表元素替换时的TypeError问题

错误原因

你遍历data['CarIds']时,每个item是列表里的字符串(比如示例中的"x"),不是字典。这时候用item['CarIds']去访问就会触发TypeError: string indices must be integers——字符串只能用整数作为索引,不能用字符串当键。

修正后的代码

方式一:通过索引遍历修改

import json

with open('./data.json') as file:
    data = json.load(file)

# 遍历列表的索引和元素,匹配到目标值就替换
for idx, item in enumerate(data['CarIds']):
    if item == 'x':
        data['CarIds'][idx] = 'abc'

# 写入新文件时加indent参数,让JSON格式更清晰
with open('./new-data.json', 'w') as file:
    json.dump(data, file, indent=4)

方式二:用列表推导式简洁替换

import json

with open('./data.json') as file:
    data = json.load(file)

# 生成新列表,替换所有"x"为"abc",其他元素保持不变
data['CarIds'] = ['abc' if item == 'x' else item for item in data['CarIds']]

with open('./new-data.json', 'w') as file:
    json.dump(data, file, indent=4)

效果验证

执行后new-data.json的内容会变成:

{
    "CarIds": [
        "abc"
    ],
    "Tariff": {
        "currency": "CAD",
        "countryCode": "CA"
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 19:39:58