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

discord.py无法向JSON文件追加内容的技术求助

解决Discord.py中JSON字典追加条目问题

问题根源

你当前的错误是因为将user、choice、message赋值为字符串类型,而字符串没有append方法;同时原有JSON结构是单个键值对,无法直接实现多条数据的追加存储。

修正方案

首先要调整JSON文件的结构,让它能存储多条报告/建议数据。初始化的JSON结构应该是包含一个列表的字典:

{
  "reports": []
}

然后修改代码,每次提交时向reports列表中追加新的条目:

async def on_submit(self, interaction: discord.Interaction):
    # 读取JSON文件,处理文件不存在的情况
    try:
        with open("reports.json", "r") as f:
            data = json.load(f)
    except FileNotFoundError:
        # 首次运行或文件不存在时初始化结构
        data = {"reports": []}
    
    answer_lower = self.answer.value.lower()
    if answer_lower in ("report", "suggestion"):
        await interaction.response.send_message("Successfully submitted your report/suggestion.", ephemeral=True)
        print(f"{interaction.user} sent a {answer_lower}: {self.answer2.value}")
        
        # 构造单条报告的字典
        new_report = {
            "user_id": str(interaction.user.id),
            "choice": answer_lower,
            "message": self.answer2.value
        }
        
        # 追加到reports列表中
        data["reports"].append(new_report)
        
        # 写入JSON文件,indent参数让格式更清晰
        with open("reports.json", "w") as f:
            json.dump(data, f, indent=4)

关键修改说明

  • 改用列表存储多条数据:将所有报告/建议存入reports列表,每条数据是一个独立字典,避免覆盖原有内容
  • 处理文件不存在的边界情况:首次运行时自动初始化JSON结构,避免报错
  • 移除错误的字符串append操作:不再单独给单个字段赋值为字符串,而是构造完整条目追加到列表
  • 优化JSON可读性:写入时添加indent=4,让生成的JSON文件格式更清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 05:55:16