Teddy
Teddy

Reputation: 101

Using a variable to read from json?

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"...
}

Upvotes: 1

Views: 139

Answers (2)

panktijk
panktijk

Reputation: 1614

You json file has strings as keys. Try:

url = data[str(random)]["url"]

Upvotes: 1

Carl Sverre
Carl Sverre

Reputation: 1188

The issue is that random.randint returns an integer number, while the dictionary you are accessing has string keys. You can solve this by wrapping str around the random variable when accessing the dictionary:

url = data[str(random)]["url"]

Upvotes: 3

Related Questions