discord.py:如何从json文件中删除值?

时间:2020-07-19 20:46:22

标签: python discord.py

我的代码:

@bot.command()
async def delwarn(ctx, member: discord.Member = None, warnid = None):
    if member:

          with open('warns.json', 'r') as fcheckifthere:
                checkifthere = json.load(fcheckifthere)
          if f'{member.id}' in checkifthere.keys():

                amount = len(checkifthere[f'{member.id}'])
                if f'{warnid}' in checkifthere[f'{member.id}']:
                    if not amount == 1:
                        
# i want to delete the value f"{warnid}"   
                         del checkifthere[f'{member.id}'][f'{warnid}']
                          with open('warns.json', 'w+') as fcheckifthere:
                              json.dump(checkifthere, fcheckifthere, sort_keys=True, indent=4)

错误:


Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: list indices must be integers or slices, not str

我想删除特定值f“ {warnid}”,但我不知道如何得到此错误。

以下是json文件的示例:

{
   305354423801217025: [
      0145324124,
      2142141244
   ]
{

1 个答案:

答案 0 :(得分:1)

您的错误在此行中,您尝试在其中删除警告ID:

del checkifthere[f'{member.id}'][f'{warnid}']

checkifthere[f'{member.id}']是一个列表,而您提供的索引是一个字符串。列表索引必须为整数,否则会出现错误。
删除列表元素的最简单方法是使用list.remove(element)

checkifthere[str(member.id)].remove(warnid)

此外,您不需要f strings,可以使用str()来转换整数并将浮点数转换为字符串。


经过一些重构,这是命令的样子:

from discord import Member
from discord.ext import commands
from json import load, dump

@bot.command()
async def delwarn(ctx, member: Member = None, warn_id: str = None):
    if not member:
        return
    with open('warns.json', 'r') as file:
        data = load(file)
        member_id = str(member.id)
    if not member_id in data.keys():
        return
    if warn_id in data[member_id] and not len(data[member_id]) == 1:
        with open('warns.json', 'w') as file:
            data[member_id].remove(warn_id)
            dump(data, file, sort_keys=True, indent=4)