Search code examples
pythonjsondiscord.pypycord

Why does in my code json pop dont work? (In python)


Let me explain my problem!

I code a Python Discord Bot and it saves the channel id and the owner id!

And if the ticket got closed it need to pop ticket!

My code looks so:

with open("data/tickets.json", "w") as f:
    data.pop(str(ctx.channel.id), f)

And the json so:

{
    "channel id 1": {
        "author": 256820568024,
        "claimed": null
    },
    "channel id 2": {
        "author": 43251524366254,
        "claimed": null
}

but if i try to close the ticket! Its delete the complete tickets.json file! Like there is nothing in it!

But i only want to delete the channel id 1 section.

And it gives me no error.

Please help me :c


Solution

  • First of all, your json script is missing a brace. It should be:

    {
        "channel id 1": {
            "author": 256820568024,
            "claimed": null
        },
        "channel id 2": {
            "author": 43251524366254,
            "claimed": null
        }
    }
    

    Then, your code is designed to do something different from your original intention. Please, consider the JSON Python module. In this way, you will load the json object so that you can manipulate your data as you wish!

    import json
    
    #read the file
    data = json.load(open("data/tickets.json","r"))
    
    #remove the object
    del (data[str(ctx.channel.id)])
    
    #if necessary, update the file
    with open('data/tickets.json', 'w') as file:
        json.dump(data,file,indent=4)
    

    Hope it helps!