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

discord.py开发中如何彻底删除JSON存储的用户提交数据而非留null值

问题原因

你之前的实现只是将submissions字典中对应用户ID的 value 赋值为None,并没有将整个键值对从字典中移除,所以序列化写入JSON文件后,会保留用户ID的键,值显示为null。

修复方案

方案1:使用del语句删除指定键(推荐,可自定义无提交时的报错提示)

需要先判断用户ID是否存在于字典中,避免删除不存在的键抛出KeyError异常,修改后的代码如下:

if config.lower() in ["delete","remove","undo","cancel"]:
    user_key = str(user.id)
    # 校验用户是否存在提交记录
    if user_key not in submissions:
        await ctx.send(embed=discord.Embed(title="ERROR", description='你还没有提交过任何内容,无法执行撤销操作!', color=discord.Color.red()))
        return
    # 彻底删除字典中对应的键值对
    del submissions[user_key]
    
    # ------------ 不要忘了添加你原有写入JSON文件的逻辑 ------------
    # 示例:
    # with open("submissions.json", "w", encoding="utf-8") as f:
    #     json.dump(submissions, f, ensure_ascii=False)

    await ctx.send(embed=discord.Embed(title="已移除当前提交", description="你的提交记录已彻底删除,随时可以重新提交新内容!", color=0xFFD700))

方案2:使用pop方法简化逻辑

如果不需要单独处理无提交记录的提示,可以直接用pop方法,不存在对应键时也不会报错:

if config.lower() in ["delete","remove","undo","cancel"]:
    submissions.pop(str(user.id), None)
    # 写入JSON文件的逻辑同上
    await ctx.send(embed=discord.Embed(title="已移除当前提交", description="你的提交记录已彻底删除,随时可以重新提交新内容!", color=0xFFD700))

修改后序列化到JSON的结果就不会再保留对应用户ID的条目,完全符合彻底删除的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 19:24:10