【问题标题】:Remove element from JSON Python从 JSON Python 中删除元素
【发布时间】:2020-11-04 16:28:38
【问题描述】:

我正在尝试为我的 discord 机器人创建一个命令,从服务器中删除一个所谓的“派系”。派系存储在一个整洁的 JSON 中,像这样

{
    "Meme Faction": {
        "members": [],
        "owner": 429935667737264139,
        "description": "This is the description :smile:",
        "member role": 773580603072839710,
        "owner role": 773580603605516290
    },
    "Gamer Faction": {
        "members": [],
        "owner": 429935667737264139,
        "description": "This is the description :smile:",
        "member role": 773580603072839710,
        "owner role": 773580603605516290
    }
}

这是应该删除派系的代码:

@commands.command(aliases=["d"])
async def delete(self, ctx, *, name: str):
    with open("configs/factions.json", "r+") as f:
        factions_json = json.load(f)
        factions_list = list(factions_json.keys()) # loads JSON keys as list

        name_capital = name.title()
        if name_capital in factions_list:
            member_role = ctx.guild.get_role(factions_json[name_capital]["member role"])
            owner_role = ctx.guild.get_role(factions_json[name_capital]["owner role"]) 

            await member_role.delete() # deletes faction role
            await owner_role.delete() # deletes faction owner role

            # JSON remove code
            factions_json.pop(name_capital) 
            f.seek(0)
            json.dump(factions_json, f, indent=4)

            await ctx.message.add_reaction("✅")

问题是,它不是从 JSON 中删除派系,而是将另一个版本的 JSON 附加到末尾,而不是派系。像这样:

{
    "Meme Faction": {
        "members": [],
        "owner": 429935667737264139,
        "description": "This is the description :smile:",
        "member role": 773580603072839710,
        "owner role": 773580603605516290
    },
    "Gamer Faction": {
        "members": [],
        "owner": 429935667737264139,
        "description": "This is the description :smile:",
        "member role": 773580603072839710,
        "owner role": 773580603605516290
    }
}{
    "Meme Faction": {
        "members": [],
        "owner": 429935667737264139,
        "description": "This is the description :smile:",
        "member role": 773580603072839710,
        "owner role": 773580603605516290
    },
}

如何覆盖 JSON 而不是附加到它?

【问题讨论】:

    标签: python json python-3.x dictionary discord.py


    【解决方案1】:

    当您以r+ 模式打开文件时,您打开它是为了读写。

    然后,您读取文件,因此流位置移动到文件末尾。

    然后,您写入文件,因此它写入当前流位置,即文件末尾。

    要解决此问题,您有两种选择:

    选项 1:

    Seek the position 使用f.seek(0) 指向文件的开头。然后写入文件。这样做的问题是它只会覆盖需要覆盖的文件以转储新的 json。文件的其余部分不会被覆盖,所以无论如何你都会得到乱码的 json。要解决此问题,您需要截断文件的其余部分。

    with open('factions.json', 'r+') as f:
        j = json.load(f)
        j.pop("Meme Faction")
        f.seek(0)
        json.dump(j, f, indent=4)
        f.truncate()
    

    给出输出:

    {
        "Gamer Faction": {
            "members": [],
            "owner": 429935667737264139,
            "description": "This is the description :smile:",
            "member role": 773580603072839710,
            "owner role": 773580603605516290
        }
    }
    

    选项 2

    关闭原始文件句柄并打开一个新的只写文件句柄。然后写入文件。

    with open('factions.json', 'r+') as f:
        j = json.load(f)
    
    j.pop("Meme Faction")
    with open('factions.json', 'w') as f:
        json.dump(j, f, indent=4)
    

    给出输出:

    {
        "Gamer Faction": {
            "members": [],
            "owner": 429935667737264139,
            "description": "This is the description :smile:",
            "member role": 773580603072839710,
            "owner role": 773580603605516290
        }
    }
    

    【讨论】:

    • OP 已经在使用您的“选项 1”,所以这不能回答问题。
    • 这就是为什么有选项 2。我仍在充实选项 1。耐心,蚱蜢! :)
    • 你会在写入后调用f.truncate() 删除文件中的额外数据,但我认为像你建议的那样打开单独的读写文件处理程序是最好的方法。
    • 选项 1 应该仍然有效。但根据OP,它不是。所以不,你还没有回答这个问题。
    • @mattficke 是的,我正在添加它。必须查看调用的函数以确保。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    相关资源
    最近更新 更多