Skip to content Skip to sidebar Skip to footer

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 error

Solution 1:

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()asyncdefafkremoveme(ctx):

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

    withopen(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 writtendel data[author]
        newData = json.dumps(data, indent=4)

        withopen(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

Post a Comment for "How Would I Delete Something From A Json File"