3

I have following json file and I need a way to randomly select json data and prints its value.

json file :

{
    "base": [{"1": "add"},{"2": "act"}],
    "past": [{"add": "added"},{"act": "acted"}],
    "past-participle": [{"add": "added"},{"act": "acted"}],
    "s-es-ies": [{"add": "adds"},{"act": "acts"}],
    "ing": [{"add": "adding"},{"act": "acting"}]
}

example

user_input = 'past' >> past
code randomly selects 'add' or 'act' from past >> add
prints out its value >> added

1 Answer 1

3

Use random.choice supplying as choices the sequence contained for the selected key:

user_input = input('> ')

> past

list(choice(j[user_input]).values())[0]
Out[177]: 'added'

Factor it in a function to make it more compact:

def random_json_val(json_obj, k):
    return list(choice(json_obj[k]).values())[0]

Calling it gets you a random value for a given k:

>>> random_json_val(j, 'past')
'added'
>>> random_json_val(j, 'past')
'acted'
>>> random_json_val(j, 's-es-ies')
'acts' 
2
  • it should be list(random.choice(json_obj[k]).values())[0] Commented Sep 12, 2016 at 21:30
  • @Scott sorry, was cooking. Yes mixed the typo, just load the json object wherever you require then pass it to the function along with the user input on which key to use. Commented Sep 12, 2016 at 21:32

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.