【问题标题】:Why does my JSON create multiple entries instead of updating them?为什么我的 JSON 会创建多个条目而不是更新它们?
【发布时间】:2021-04-22 17:57:10
【问题描述】:

我有一个命令,您可以在其中输入正确答案。如果正确,用户将获得 JSON 中的积分。但是我的更新功能似乎被破坏了,因为在再次正确执行之后,在 JSON 中再次为同一用户创建了一个条目。但是,我只想更新积分。此外,JSON 在关于用户的第二个条目之后停止。出了什么问题?

代码:

correct_answers = "A"

# Open the JSON after start
def json_open():
    with open('users.json', 'r', encoding='utf-8') as f:
        users = json.load(f)
        return users


class Questions(commands.Cog, name='Question'):
    """Question bot"""

    def __init__(self, bot):
        super().__init__()
        self.bot = bot


    @commands.command()
    async def question(self, ctx, answer):
        self.question.enabled = False
        global correct_answers
        if correct_answers != answer:
            await ctx.author.send(f"You guessed {answer} which is **wrong**. Good luck next time!")
            await ctx.message.delete()
            return
# OPEN JSON FILE, LOAD DATA
        with open('users.json', 'r') as f:
            users = json.load(f)
        await self.update_data(users, ctx.message.author)
        await self.add_experience(users, ctx.message.author, 10)
        with open('users.json', 'w') as f:
            json.dump(users, f)
            await ctx.message.delete()
# UPDATE DATA
    async def update_data(self, users, user):
        if not user.id in users:
            users[user.id] = {}
            users[user.id]['Points'] = 0
            #users[user.id]['level'] = 1

    async def add_experience(self, users, user, exp):
        users[user.id]['Points'] += exp

看起来最后一个函数不起作用还是不需要add_experience 函数?

第二次执行后的 JSON 如下所示:

{"MYID": {"Points": 10}, "MYIDAGAIN": {"Points": 10}}

【问题讨论】:

    标签: json discord discord.py


    【解决方案1】:

    不知何故,它被转换成str,所以你必须稍微更新一下函数。为了更好地解释它: 将user.id 变成str

        async def update_data(self, users, user):
            key = str(user.id)
            if key not in users:
                users[key] = {}
                users[key]['Points'] = 0
    
        async def add_experience(self, users, user, exp):
            users[str(user.id)]['Points'] += exp
    

    也许还可以查看解释问题的page

    【讨论】:

      【解决方案2】:

      我认为您必须像这样将用户 ID 字符串化

      users[str(user.id)]['Points'] += exp
      

      【讨论】:

      • 这给了我一个 KeyError 和我的 UID。
      • 这可能意味着它没有在json文件中找到UID。要解决这个问题,你可以这样做except KeyError: users[str(user.id)]['Points'] = exp
      猜你喜欢
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      相关资源
      最近更新 更多