[Python] How can I index search a JSON file with different elements in Python

Discussão em 'Python' iniciado por Stack, Agosto 19, 2025.

  1. Stack

    Stack Membro Participativo

    In this python script I am trying to randomly access one of the components in this JSON file, however I repeatedly receive a "Keyerror".

    Here is the code:

    import json

    def genCard():
    with open("cards.json", "r") as file:
    cards = json.load(file)
    x = random.randint(0, len(cards["cards"]) - 1)
    card = cards["cards"][str(x)] ## Have also used ["cards"][x]
    print(card)
    return card


    Here is a section of the JSON file.

    {
    "cards": {
    "25": {
    "id": 25,
    "name": "Aliks",
    "image": "Aliks.png",
    "group": "Summer",
    "atk": 6,
    "def": 4,
    "int": 8,
    "spd": 4,
    "agl": 7
    },
    "113": {
    "id": 113,
    "name": "Nichel",
    "image": "PlaceHolder.png",
    "group": "Summer",
    "atk": 7,
    "def": 5,
    "int": 7,
    "spd": 5,
    "agl": 6
    },
    "27": {
    "id": 27,
    "name": "Arian",
    "image": "PlaceHolder.png",
    "group": "Summer",
    "atk": 8,
    "def": 6,
    "int": 3,
    "spd": 6,
    "agl": 7
    }
    }
    }


    I simply want to pick a random card from this JSON list, any help?

    Here is the error report, I am using a discord library to develop a discord application.

    Traceback (most recent call last):
    File "c:\Users\Gamer\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Development\Stuff\Discord Bots\TestThingForNow\discordBot", line 109, in pull
    card = genCard()
    File "C:\Development\Stuff\Discord Bots\TestThingForNow\discordBot", line 43, in genCard
    card = cards["cards"][x] ## Have also used ["cards"][x]
    ~~~~~~~~~~~~~~^^^
    KeyError: 1

    The above exception was the direct cause of the following exception:

    Traceback (most recent call last):
    File "c:\Users\Gamer\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\ext\commands\bot.py", line 1366, in invoke
    await ctx.command.invoke(ctx)
    File "c:\Users\Gamer\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
    await injected(*ctx.args, **ctx.kwargs) # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "c:\Users\Gamer\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
    raise CommandInvokeError(exc) from exc
    discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 1

    Continue reading...

Compartilhe esta Página