Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

python - How would i delete something from a json file

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!

no errors

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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...")

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

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

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 Dictionaries, Python-Json


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...