Mohammad Zamanian Mohammad Zamanian - 1 year ago 128
JSON Question

selecting random json element

python 3.5

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



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

(result would be C or B)


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"]
if x == "":
print("nothing found")
else :

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 Source

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']
    x = random.choice(values)
except IndexError:
    print("nothing found")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download