I'm trying to get my Python bot to use a variable I already defined (random), to read a JSON file and send me the URL that corresponds to the variable it was given.
with open('data.json', 'r') as json_data:
data = json.load(json_data)
max = data["max"]["max"]
random = random.randint(1, max)
url = data[random]["url"]
But when I run the bot it goes all "KeyError", and after checking by replacing url[random]["url"] by url["5"]["url"] it correctly sent me the url that corresponds to 5
I'm not sure if it's impossible to do what I'm trying to do this way, or if there's some kind of special format I have to use:
here's my question, and I really don't know how to phrase it properly since I don't know the terminology so:
Is there a simple way to use this "random" variable when asking my bot to read from a json ?
I'd rather use this kind of formating since it's something I understand and am used to but if it's not possible I don't mind trying something else
If you're wondering how the json looks like it goes a bit like :
{
"max": {"max":139},
"1": {stuff here},
"2": {stuff here},
"3": {stuff here},
"4": {stuff here},
"etc"...
}
random.randintreturns an integer (as the name implies). You need to convert it to a string. Also don't call itrandom, it will stomp on the name of the module.rdm = str(random.randint(1, max)). Edit: Don't usemaxas a variable name either- it will overwrite__builtin__.max.