Search code examples
jsondiscorddiscord.pykeyerror

How can I fix a key error in a JSON or delete an entry out of it?


I have an economy system and in this various things are stored in a JSON.

There is a wallet and bank amount. I have uploaded the whole thing to Gitlab, so the JSON will not be readable.
Since I upgraded my bot, which runs with the Red instance, I get a KeyError for 2 users, but also only for a specific query. As an example I have the following command:

    @commands.command()
    async def wallet(self, ctx, user: discord.Member = None):
        """Check the wallet amount"""
        if user is None:
            with open(f'{bundled_data_path(self)}/mainbank.json', 'r') as f:
                data = json.load(f)
                user = ctx.author
                users = await get_bank_data()
                wallet_amt = users[str(user.id)]["wallet"]
                await ctx.send(f "**You have {wallet_amt} coins in your wallet.**")

However, if I now want to query the value of ["bank"] I get a KeyError: ' bank' for the users that were stored in the JSON before the update, this does not apply to wallet. I am still relatively new to a JSON, but is it possible to delete the data from the JSON or add a key by a command?

Maybe the following definition will also help:

async def open_account(user):
    users = await get_bank_data()

    if str(user.id) in users:
        return False
    else:
        users[str(user.id)] = {}
        users[str(user.id)]["wallet"] = 0 # Goes in one command
        users[str(user.id)]["bank"] = 0 # Does not work

    with open('data/mainbank.json', 'w') as f:
        json.dump(users, f)
    return True

My approaches would be/were:

  • Try something with .remove(TheUserID) - This is to delete the whole information for the user
  • del something out of the JSON
  • I also read some different posts but I am not sure whether they will work: 1 & 2

Maybe someone here can tell me if my approaches are the right way to form the whole thing into a command which will for example remove the (user.id) out of the JSON.


Solution

  • In my experience, JSON key errors usually meant two things:

    1. The key doesn't exist
    2. The key can't be found in the current nest

    Because JSON is often nested, you need to be on the right level to retrieve values.
    Check for both of those things; you may not need to alter with the existing data.

    To answer your JSON related stuff:

    How to add a key-value to JSON data retrieved from a file with Python?
    Delete an element in a JSON object