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
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()