1

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?

1
  • 3
    you might want to parse content first: import json; json.loads(f) ... Commented May 7, 2016 at 1:23

2 Answers 2

1

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")
Sign up to request clarification or add additional context in comments.

Comments

0

Here is one solution:

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.