使用Python测试JSON中的值

2024-09-24 10:23:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个文件中有这个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实现的方法吗?你知道吗


Tags: 文件信息jsonokgreenbluecolorprint
2条回答

这里有一个解决方案:

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)

你肯定有正确的想法:正如你所指出的,只是语法错误。你知道吗

如注释所示,您需要使用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")

相关问题 更多 >