1

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"...
}
1
  • 4
    random.randint returns an integer (as the name implies). You need to convert it to a string. Also don't call it random, it will stomp on the name of the module. rdm = str(random.randint(1, max)). Edit: Don't use max as a variable name either- it will overwrite __builtin__.max. Commented Sep 21, 2018 at 20:08

2 Answers 2

3

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"]
Sign up to request clarification or add additional context in comments.

2 Comments

Also as @pault mentioned in his comment, don't name your variable the same as a module to prevent future code from failing.
It's worth noting that JSON will not accept ints as keys. They automatically get converted to strings. Bitten by that before :)
1

You json file has strings as keys. Try:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.