gpt4 book ai didi

python - 使用 Python 测试 JSON 中的值

转载 作者:太空宇宙 更新时间:2023-11-03 16:37:39 25 4
gpt4 key购买 nike

我在文件中有这个 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中做到这一点吗?

最佳答案

您的想法肯定是正确的:正如您所指出的,只是语法错误。

正如评论所建议的,您需要使用 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")

关于python - 使用 Python 测试 JSON 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37083513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com