Scott Scott - 2 months ago 11
JSON Question

How to select json data randomly

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

Jim Jim
Answer

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'