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

Python删除JSON内_notes数组_type=1元素报错,求助解决

问题:删除JSON数组中指定条件元素时报错

尝试删除JSON对象中_notes数组内_type值为1的元素,但运行Python脚本时持续报错,不清楚错误含义及解决方法。

精简后的JSON数据

{
    "_notes": [
        {
            "_time": 10,
            "_lineIndex": 2,
            "_lineLayer": 0,
            "_type": 0,
            "_cutDirection": 7
        },
        {
            "_time": 12,
            "_lineIndex": 2,
            "_lineLayer": 0,
            "_type": 1,
            "_cutDirection": 1
        },
        {
            "_time": 14,
            "_lineIndex": 2,
            "_lineLayer": 1,
            "_type": 1,
            "_cutDirection": 0
        }
    ]
}

我的Python脚本

#!/usr/bin/python3

import json
obj = json.load(open("ExpertPlusStandardd.dat"))

for i in range(len(obj["_notes"])):
    print(obj["_notes"][i]["_type"])
    if obj["_notes"][i]["_type"] == 1:
        obj.pop(obj["_notes"][i])

open("test.dat", "w").write(
    json.dumps(obj, indent=4, separators=(',', ': '))
)

报错信息

回溯(最近的调用最后):
  文件 "C:\programming\python\train_one_hand\run.py", 第9行, 在 <module> 中
    obj.pop(obj["_notes"][i])
TypeError: 不可哈希的类型:'dict'

错误原因分析

  1. obj.pop()用法错误:obj是JSON解析后的顶层字典,pop()方法需要传入字典的键名(字符串类型),但你传入的是_notes数组里的字典元素,而字典属于不可哈希类型,因此触发类型错误。
  2. 遍历数组时直接删除元素的隐患:就算把obj.pop()改成obj["_notes"].pop(i),也会因为数组长度动态变化,导致后续遍历的索引错位,可能跳过目标元素或者引发索引越界。

正确解决方案

推荐用列表推导式直接生成过滤后的新数组,写法简洁且完全避免索引问题:

#!/usr/bin/python3

import json

# 读取JSON文件,用with自动管理文件资源
with open("ExpertPlusStandardd.dat", "r") as f:
    obj = json.load(f)

# 过滤掉_type为1的元素,重新赋值给_notes
obj["_notes"] = [note for note in obj["_notes"] if note["_type"] != 1]

# 写入新文件
with open("test.dat", "w") as f:
    json.dump(obj, f, indent=4, separators=(',', ': '))

补充方案(循环删除)

如果一定要用循环方式删除,建议倒序遍历数组索引,这样删除元素不会影响未遍历到的元素位置:

#!/usr/bin/python3

import json

with open("ExpertPlusStandardd.dat", "r") as f:
    obj = json.load(f)

# 倒序遍历索引,从最后一个元素往前处理
for i in range(len(obj["_notes"])-1, -1, -1):
    if obj["_notes"][i]["_type"] == 1:
        obj["_notes"].pop(i)

with open("test.dat", "w") as f:
    json.dump(obj, f, indent=4, separators=(',', ': '))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 23:45:35