Scott Scott - 6 months ago 27
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"}]


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

Jim Jim

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

user_input = input('> ')

> past

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')
>>> random_json_val(j, 'past')
>>> random_json_val(j, 's-es-ies')