如何从JSON删除键和值

时间:2020-09-23 17:11:49

标签: python python-3.x discord.py discord.py-rewrite

我正在为自己的机器人制作标签功能,并且设法制作了用于创建,使用和显示标签的命令。现在,我停留在如何根据给定的标记删除键和值。例如,!deletetag youtube将从下面的列表中删除youtube标签:

{
    "twitch": "https://www.twitch.tv/",
    "youtube": "https://www.youtube.com/",
    "ig": "https://www.instagram.com/",
    "twitter": "https://twitter.com/"
}

我使用JSON文件存储标签的原因是因为该漫游器仅可用于<100人的一台服务器,并且不会包含超过30至40个标签。这是我尝试过的:

@commands.command(name="deletetag",
                  help="Delete an existing tag.")
async def _deletetags(self, ctx, tag: str):
    with open('tags.json') as output:
        data = json.load(output)
        for key in data:
            del key[tag]

1 个答案:

答案 0 :(得分:1)

将我的评论作为答案,以方便参考。

# Remove key from dictionary
del data[tag]

# Serialize data and write back to file
with open('tags.json', 'w') as f: 
    json.dump(data, f)