我如何从json文件中删除某些内容 [英] How would i delete something from a json file

查看:153
本文介绍了我如何从json文件中删除某些内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定如何从.json文件中删除内容

I'm not sure how to delete something from a .json file

我尝试查找它,但还是没什么:(

I've tryed looking it up and it still nothing :(

@bot.command()
async def afkremoveme(ctx):
#pls help me I'm lost!

没有错误

推荐答案

我不确定您要命令执行什么操作,但这是如何将json实现到discord.py中的示例.

I'm not sure what you want your command to do, but here's an example of how you would implement json into discord.py.

在这里,无论何时执行命令,机器人都会打开一个json文件,读取数据,并查看消息作者是否在数据中.如果作者在数据中,则将键/值对删除,并将数据重写到json文件中:

Here, whenever the command is executed, the bot opens a json file, reads the data, and sees if the message author is in the data. If the author is in the data, the key/value pair is deleted, and the data is rewritten into the json file:

import json

@bot.command()
async def afkremoveme(ctx):

    f = "yourFile.json"
    author = str(ctx.author.id)

    with open(f, "r") as read_file:
        data = json.load(read_file)

    if author in data: # if any key in the dictionary is an integer, it is converted to a string when a json file is written

        del data[author]
        newData = json.dumps(data, indent=4)

        with open(f, "w") as write_file:
            write_file.write(newData)

        await ctx.send(f"{ctx.author.display_name} is no longer afk...")

这正在读取一个看起来像这样的json文件(用您的ID替换000000):

This is reading a json file that looks like this (replace 000000 with your id):

{
    "000000" : "afk",
    "someOtherGuy" : "afk"
}

所有这些都使用字典和json模块.如果您不熟悉这两个概念,这里有一些链接可以帮助您:-)

All of this uses dictionaries and the json module. If you're unfamiliar with either of the concepts, here are a few links to help you out :-)

Python字典 Python-Json

这篇关于我如何从json文件中删除某些内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆