O. Watson O. Watson - 1 month ago 9
JSON Question

Parsing through JSON file with python and selecting multiple values on certain conditions

I have this JSON file.

{
"reviewers":[
{
"user":{
"name":"keyname",
"emailAddress":"John@email",
"id":3821,
"displayName":"John Doe",
"active":true,
"slug":"jslug",
"type":"NORMAL",
"link":{
"url":"/users/John",
"rel":"self"
},
},
"role":"REVIEWER",
"approved":true
},
{
"user":{
"name":"keyname2",
"emailAddress":"Harry@email",
"id":6306,
"displayName":"Harry Smith",
"active":true,
"slug":"slug2",
"link":{
"type":"NORMAL",
"url":"/users/Harry",
"rel":"self"
},
},
"role":"REVIEWER",
"approved":false
}
],
}


Initially, I was using a snippet of code that would go through and grab the full names of the reviewers.

def get_reviewers(json):
reviewers = ""
for key in json["reviewers"]:
reviewers += key["user"]["displayName"] + ", "
reviewers = reviewers[:-2]
return reviewers


which would return
"John Doe, Harry Smith"
. However, now I'm trying to get it so that the script will return a (A) next to the name of the user if their tag equals true
"approved"=true
.

So for example the code above would get the names, then see that John's approved tag is true and Harry's is false, then return
"John Doe(A), Harry Smith"
. I'm just not sure where to even begin to do this. Can anyone point me in the right direction?

This is what I've been trying so far but obviously it isn't working as I'd like it to.

def get_reviewers(stash_json):
reviewers = ""
for key in stash_json["reviewers"]:
if stash_json["reviewers"][0]["approved"] == true:
reviewers += key["user"]["displayName"] + "(A)" + ", "
else:
reviewers += key["user"]["displayName"] + ", "
reviewers = reviewers[:-2]
return reviewers


which outputs
Jason Healy(A), Joan Reyes(A)


This is what my
stash_json
outputs when put through pprint.

Answer

You probably want something along the lines of this:

def get_reviewers(stash_json):
    reviewers = ""
    for item in stash_json["reviewers"]:
        if item["approved"]:
            reviewers += item["user"]["displayName"] + "(A)" + ", "
        else:
            reviewers += item["user"]["displayName"] + ", "
    reviewers = reviewers[:-2]
    return reviewers

I think part of your confusion comes from the fact that "reviewers" is a list of dict elements, and each dict element has a key-value approved, but also a key "user" which value itself is another dict.


Read the JSON file carefully, and for debugging purposes, use plenty of

print(...)
print(type(...))   # whether something is a dict, list, str, bool etc

or

from pprint import pprint    # pretty printing
pprint(...)