Mohammad Zamanian Mohammad Zamanian - 3 months ago 15
JSON Question

selecting random json element

python 3.5

hi i have following json file and i want to select json data random...

json

{"x":[
{"A":"B"},
{"A":"C"},
{"F":"H"}
]}


select data where item in data['x'] is A

(result would be C or B)

code

data = json.load(open('j.json'))
x = ""
for item in data["x"]:
T = True if "A" in item else False
if T is True:
x = item["A"]
#break
else:
pass
if x == "":
print("nothing found")
else :
print(x)


when i break it , it just prints B every time i run script
i want it to select B or C random
any ideas?!

Answer

Perhaps this program will answer your (not-yet-asked) question:

import json
import random

data = json.load(open('j.json'))
values = [v for d in data['x'] for k,v in d.items() if k == 'A']
try:
    x = random.choice(values)
    print(x)
except IndexError:
    print("nothing found")