0

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.

8
  • 1
    I think you want == True, not == "true", assuming you're parsing the JSON properly. Commented Oct 13, 2016 at 4:29
  • With the suggested correction, the line if stash_json["reviewers"][0]["approved"]: will always have the same result, since you've fixed the list index there. Perhaps you want if key['approved']:? Commented Oct 13, 2016 at 4:31
  • Btw, don't explicitly compare to True. The truthiness of the value itself is enough: use if stash_json["reviewers"][0]["approved"]: instead of if stash_json["reviewers"][0]["approved"] == True:. Commented Oct 13, 2016 at 4:32
  • I think if key["approved"]: is what you want. Commented Oct 13, 2016 at 4:33
  • @Evert I see what you're saying but am having a little bit of trouble actually implementing it, would you be able to post an example? Thanks. Commented Oct 13, 2016 at 4:34

2 Answers 2

2

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

5 Comments

On my end that's returning John Doe(A), Harry Smith(A), but i'm getting closer to the result I want.
@O.Watson That'll be because you're using a different JSON reader than the Python stdlib module. If I use the stdlib json module, I can't even read your JSON file, as it contains trailing commas. Presumably, your JSON reader translates true to something like "true", so possibly you need to change that comparison (e.g. if item["approved"] == "true":). Better, however, is to fix your JSON file and use the stdlib json module instead to read it.
==, not =, but yeah, hard to know what's going on without seeing the code that parses the JSON
@smarx Tx; just within the 2 mins grace editing period. Are typos in comments allowed? ;-)
Oh my god of course, bit of a silly mistake, let me post the proper JSON
0

This looks like a good place to use join and list comprehension:

def get_reviewers(stash_json):
   return ", ".join([item['user']['displayName'] + ('(A)' if item['approved'] else '') for item in stash_json['reviewers']])

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.