Search code examples
pythonjsondiscord.pykeyerror

KeyError Json in Python fix


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

data[str(ticket.id)]["author"] = ctx.author.id

with open("data/tickets.json", "w") as f:
    json.dump(data, f, indent=4)

I want to create in a json file, the ticket id and the author of this ticket. But i want it looks so:

{
    "random_channel_id" {
        "author": "random_user_id"
    }
}

But its give me this error:

Traceback (most recent call last):
  File "C:\Users\omalo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 383, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\omalo\OneDrive\Desktop\Home Bot\cogs\Ticket.py", line 46, in TicketCreation
    data[str(ticket.id)]["author"] = ctx.author.id
KeyError: '995020823683412029'

Solution

  • From my testing and knowledge, the issue is that you are trying to create the author key in a nested dictionary that does not exist, which is not possible.

    >>> x = {}
    >>> x[123]['author'] = 456
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 123
    

    So if you create the key 123 first (or in your case, the ticket id), but with an empty dictionary, and then the author key in the nested dictionary, it will work:

    data[str(ticket.id)] = {}
    data[str(ticket.id)]["author"] = ctx.author.id
    

    Alternatively; you could also do it at once:

    data[str(ticket.id)] = {"author" : ctx.author.id}