使用Python

时间:2016-05-07 01:22:40

标签: python json python-3.x

我在文件中有这个JSON:

{"groupcolor":[
    {"user":"group01", "color":"blue"},
    {"user":"group02", "color":"yellow"},
    {"user":"group03", "color":"green"}
]}

我想使用Python(3)来验证“user”的内容是否与“color”匹配。我试过了:

import json 

with open('groupcolor.json') as f:
    for line in f:
        if f.user == group01 and f.color = blue:
            print("ok!")
        else:
            print ("not ok")

但它显然不是正确的语法。我发现的大部分信息都集中在解析或添加信息上,但我还没有发现任何关于检查两个元素之间关系的信息。是用Python做的一种方法吗?

2 个答案:

答案 0 :(得分:1)

你肯定有正确的想法:正如你指出的那样,只是错误的语法。

如评论所示,您需要使用json.load()(但不是json.loads(),因为json.loads()用于字符串,而不是文件)。这将作为字典在json文件中绑定。

import json 

with open('groupcolor.json') as f:
    json_dict = json.load(f)
    users = json_dict["groupcolor"]
    for item in users:
        if item["user"] == "group01" and item["color"] == "blue":
            print("ok!")
        else:
            print ("not ok")

答案 1 :(得分:0)

这是一个解决方案:

import json 

with open('groupcolor.json') as f:
    group_color = json.load(f)  # parse json into dict

group_color = group_color["groupcolor"]  # get array out of dict

# create a dictionary where user is group01 and color is blue
search_criteria = dict(zip(("user", "color"), ("group01", "blue")))
for user_data in group_color:
    message = "ok!" if user_data == search_criteria else "not ok"
    print(message)