0

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
7
  • 1
    Please edit your question to include the full error message, fix the indentation in the first code block, and include the necessary imports. Commented Aug 19 at 17:10
  • 1
    Work backwards. start by seeing what the value of the key is that your code is trying to access the json with Commented Aug 19 at 17:14
  • your error is KeyError: 'an int value' isn't it ? as said before this because the map doesn't have the random key Commented Aug 19 at 17:18
  • @bruno yeah it is Commented Aug 19 at 17:19
  • 2
    maybe you should get keys = cards["cards"].keys() and use x = random.choice(keys) Commented Aug 19 at 17:20

1 Answer 1

1

You're getting a KeyError whenever the random numerical value of x doesn't correspond to a key in the JSON data. E.g.: the JSON you gave has keys "25", "113", and "27", so if x is anything other than one of those values, you'll get an error.

What you can do instead is get a list of the keys (i.e. those numbers) in the "cards" section, and use random.choice to pick from one of the available keys.

import json
import random


def genCard():
    with open("cards.json", "r") as file:
        cards = json.load(file)
        keys = cards["cards"].keys()  # get the names of all the keys in the "cards" section
        x = random.choice(list(keys))  # choose one of those keys at random
        card = cards["cards"][x]
        print(card)
        return card


genCard()
Sign up to request clarification or add additional context in comments.

1 Comment

Glad to help! And if it helps to clarify any further, any JSON you load into Python becomes a dictionary and can be handled like any other Python dict from that point.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.