繁体   English   中英

列表索引必须是整数,而不是使用 json 时的切片

[英]List indices must be integers, not slice while using json

代码:

@bot.command()
async def start(ctx):
    edit = []
    file = open("wallet.json", "r+")
    for line in file:
        temp = json.loads(line)
        edit.append(temp)

    userid = []
    for i in range(len(edit)):
        userid.append(edit[i]["id"])

    user = str(ctx.author.id)
    if userid.count(user) > 0:
        await ctx.reply("You already have an account")
    else:
        embed = nextcord.Embed(title = "Blablabla", description = "Blablabla")
        embed.set_footer(text = "Blablabla")
        await ctx.send(embed = embed)

        entry = {"id": user, "gold": 0, "fyre": 0, "faction": None}

    json.dump(entry, file)

json:空

错误:

userid.append(edit[i]["id"])
TypeError: list indices must be integers or slices, not str

本质上,我正在尝试制作一个 json 文件,每次运行此 Discord 命令时都会添加一个对象。 您可以忽略其中包含“Nextcord”、“Embed”和“ctx”字样的所有内容。 当我运行命令时,json 会在数组中获取一个对象。 这会导致我的 for 循环向用户 ID 列表添加内容以获取 Typeerror,因为它旨在加载大量对象,而不是数组。

在 wallet.json 里面:

[{"id": "My Discord ID, in my real code it's there", "gold": 0, "fyre": 0, "faction": null}]

我的代码的另一部分做类似的事情完美无缺,所以这段代码一定有问题。 请帮忙。

这里的问题是您加载 json 错误; 因此您的userid列表为空。 下面的代码片段正确地填充了您的userid变量:

@bot.command()
async def start(ctx):
    file = open("wallet.json", "r+")
    edit = json.load(file)

    userid = [i["id"] for i in edit]

    user = str(ctx.author.id)
    if userid.count(user) > 0:
        await ctx.reply("You already have an account")
    else:
        embed = nextcord.Embed(title = "Blablabla", description = "Blablabla")
        embed.set_footer(text = "Blablabla")
        await ctx.send(embed = embed)

        entry = {"id": user, "gold": 0, "fyre": 0, "faction": None}

    json.dump(entry, file)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM