inessadl inessadl - 6 months ago 9
Python Question

Test values inside JSON using Python

I have this JSON in a file:

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


and I want to use Python(3) to verify if the content of "user" matches with "color". I've tried:

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")


but it obviously isn't the right syntax. most of the information that I found is focused on parsing or adding information, but I haven't found anything about checking the relation between two elements. is a way to do it in Python?

Answer

You definitely have the right idea: just the wrong syntax, as you point out.

As a comment suggests, you need to use json.load() (but not json.loads(), as json.loads() is for a string, not a file). This will rope in the json file as a dictionary.

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")
Comments