python 3.5
嗨我有以下json文件,我想随机选择json数据......
JSON
{"x":[
{"A":"B"},
{"A":"C"},
{"F":"H"}
]}
选择数据['x']中的项为A
的数据(结果将是C或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"]
#break
else:
pass
if x == "":
print("nothing found")
else :
print(x)
当我打破它时,它只会在每次运行脚本时打印B. 我希望它随机选择B或C 任何想法?!
答案 0 :(得分:0)
也许这个程序会回答你的(尚未提出的)问题:
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")