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

如何在循环中修改JSON文件值?实现用户警告次数递增

实现警告次数递增功能

核心实现代码

import json
import os
from discord.ext import commands

@commands.command()
async def warn(self, ctx: commands.Context, member: discord.Member):
    # 初始化或读取警告数据
    if not os.path.exists('warns.json'):
        data = {"users": {}}
    else:
        with open('warns.json', 'r', encoding='utf-8') as f:
            data = json.load(f)
    
    user_id_str = f"{member.id}"
    # 更新警告次数
    if user_id_str in data["users"]:
        # 字符串转整数运算后再转回字符串
        current_count = int(data["users"][user_id_str])
        data["users"][user_id_str] = str(current_count + 1)
    else:
        # 首次警告,初始化为1
        data["users"][user_id_str] = "1"
    
    # 将更新后的数据写回文件
    with open('warns.json', 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=4)
    
    # 反馈结果给用户
    await ctx.send(f"{member.mention} 已被警告,当前警告次数:{data['users'][user_id_str]}")

关键细节说明

  • 文件读写逻辑:读取用'r'模式,写入用'w'模式,确保更新后的内容覆盖原文件
  • 类型转换处理:你的JSON中警告次数以字符串存储,必须先转为整数完成加法运算,再转回字符串存回,避免类型错误
  • 边界场景兼容:自动处理用户首次被警告的情况,避免KeyError;同时检查文件是否存在,不存在则自动初始化空的警告结构
  • 格式可读性:写入文件时用indent=4参数,让JSON文件保持清晰的缩进格式,方便后续手动查看或修改

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 07:36:20