Scott Scott - 1 year ago 74
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
Answer Source

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')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download