How to select json data randomly
<p>I have following json file and I need a way to randomly select json data and prints its value. </p>

<p><strong>json file :</strong></p>

<pre><code>{
    "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"}]
}
</code></pre>

<p><strong>example</strong></p>

<pre><code>user_input = 'past' &gt;&gt; past
code randomly selects 'add' or 'act' from past &gt;&gt; add
prints out its value &gt;&gt; added
</code></pre>

<p>Use <code>random.choice</code> supplying as choices the sequence contained for the selected <code>key</code>:</p>

<pre><code>user_input = input('&gt; ')

&gt; past

list(choice(j[user_input]).values())[0]
Out[177]: 'added'
</code></pre>

<p>Factor it in a function to make it more compact:</p>

<pre><code>def random_json_val(json_obj, k):
    return list(choice(json_obj[k]).values())[0]
</code></pre>

<p>Calling it gets you a random value for a given <code>k</code>:</p>

<pre><code>&gt;&gt;&gt; random_json_val(j, 'past')
'added'
&gt;&gt;&gt; random_json_val(j, 'past')
'acted'
&gt;&gt;&gt; random_json_val(j, 's-es-ies')
'acts' 
</code></pre>

python json python-3.x