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

如何修改JSON元素值?解决Python列表索引报错问题

修复JSON修改代码中的"list indices must be integers or slices, not str"错误

问题背景

需要修改JSON数据中locations数组最后两个元素的time_window值,原始JSON结构如下:

{
   "locations":[
      {
         "depot_duration_s":90,
         "depot_id":"depot_1",
         "time_window":"09:00-20:00",
         "type":"delivery"
      },
      {
         "depot_duration_s":90,
         "depot_id":"depot_1",
         "time_window":"09:00-20:00",
         "type":"delivery"
      },
      {
         "depot_duration_s":90,
         "depot_id":"depot_1",
         "time_window":"09:00-20:00",
         "type":"delivery"
      }
   ]
}

尝试的代码出现list indices must be integers or slices, not str错误:

import json

with open('C:/Users/8_31_file.json', 'r+', errors = "ignore") as myData:
    myData = json.load(myData)
    mylist = myData["locations"][-2:]
    mylist["time_window"] = "17:00-20:00"
    mylist = {'locations':mylist}
    print(mylist)

错误原因

myData["locations"][-2:]取到的是列表类型(包含locations数组最后两个字典元素),直接用字符串"time_window"作为索引给列表赋值,而列表仅支持整数或切片作为索引,因此触发报错。

修复后的代码

遍历切片得到的列表,对每个字典元素单独修改time_window字段:

import json

with open('C:/Users/8_31_file.json', 'r+', errors="ignore") as file:
    # 加载JSON数据
    data = json.load(file)
    # 获取最后两个location元素
    target_locations = data["locations"][-2:]
    # 逐个修改time_window值
    for loc in target_locations:
        loc["time_window"] = "17:00-20:00"
    # 将修改后的数据写回文件(不需要写回可删除以下三行)
    file.seek(0)
    json.dump(data, file, indent=4)
    file.truncate()
    # 打印修改结果
    print(json.dumps(data, indent=4))

补充说明

  • 修复核心:针对列表中的每个字典元素单独修改字段,而非直接对列表操作
  • 新增写回文件的逻辑,避免修改后的数据仅停留在内存中
  • 保留原JSON的结构完整性,未破坏原有数据格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 22:25:32