think-maths
think-maths

Reputation: 967

Selecting random greeting from reading a JSON file using python

I have a JSON file looking like this which i have to randomise so that every time any input comes it shows any random output from the 3 in the json file.

{
    "1":"Welcome",
    "2":"Hello",
    "3":"Hi"
}

I read the JSON file

greeting_template1=readjson(input_file_path+'greeting_template1.json')

and to randomise

greeting_template1 = random.choice(greeting_template1)

But I am getting the error:

   greeting_template1 = random.choice(greeting_template1)
  File "C:\Users\\AppData\Local\Continuum\anaconda3\envs\lib\random.py", line 262, in choice
    return seq[i]
KeyError: 2

Please highlight where I am going wrong

Upvotes: 0

Views: 507

Answers (2)

anas17in
anas17in

Reputation: 161

As others have pointed out your JSON is not valid. Valid json file would be:

{
    "1":"Welcome",
    "2":"Hello",
    "3":"Hi"
}

And the code to get a random would look something like:

import json
import random

with open('greeting_template1.json') as json_file:
    data = json.load(json_file)

random_greeting = data[random.choice(list(data))]

The reason you are getting error is because random.choice() needs a sequence as an argument. Parsing a json gives you a python dictionary which is not a sequence.

Upvotes: 1

Aquarthur
Aquarthur

Reputation: 619

Your document has 3 JSONs in it, not one. Once you close the initial {, that is your JSON. You need to rewrite to:

{
    "1":"Welcome",
    "2":"Hello",
    "3":"Hi"
}

Upvotes: 0

Related Questions