How to compare the json value with dictionary in python

Question:

I have JSON like this.

{
  "currentdatetime": "11",
  "syncinterval_seconds": 4,
  "public_keys": [
    {
      "system": "aa",
      "pubkey": "aa"
    }
  ],
  "users": [
    {
      "username": "user",
      "user_id": "user",
      "realname": "user_10",
      "emailaddress": "[email protected]",
      "accountenabled": false,
      "mustchangepassword": false,
      "passwordhash": "$E6gi",
      "accesslevel": [
         "WORKER"
      ],
      "expiration": "2022-11-02T16:21:52",
      "site_specific": false,
      "symkey": "aaaa",
      "privatekey": "aaa"
    },
  ]
}

and I created a dictionary like this which maps usernames to their respective access level

user_access = {
  "user": "WORKER",
  "user2": "ADMIN",
  "user3": "WORKER",
  "user4": "GENERAL"
}

I am trying to verify in my API response json that the defined user has the correct access level.

I wrote a function like this

 def LoadUserList(apijson)
     for user_result in apijson[USERS]:
         username = user_result[USER_NAME]
         accesslevel = user_result[accesslevel]
         if (user_result[USER_NAME] == 'user' AND user_result[accesslevel] == 'WORKER')
             print "success"
         else
             print "not matching"

But the above code is not working as expected. I don’t know how to compare the values in the JSON with the values in the dictionary. How do I fix my code so that it prints "success" for each user in the JSON that has a matching accesslevel value in the user_access dictionary?

Asked By: user3354840

||

Answers:

Assuming apijson is a dict, e.g., generated by applying json.loads() on API result:

def LoadUserList(apijson)
    for user in apijson['users']:
        username, accesslevel = user['username'], user['accesslevel']
        if user_access.get(username) in accesslevel:
            print(username, "success")
        else
            print(username, "not matching")
Answered By: msamsami

Dictionaries in python have 2 ways of accessing values by some key.

  1. via hard bracket indexers – apijson["users"]
  2. via .getapijson.get("users")

Note that both are case-sensitive and both are using quotes to pass the values as strings rather than variable names. USERS = "users"; apijson[USERS] would be fine as well but USERS would need to first be defined.

Additionally –

  1. We love colons in python so def LoadUserList(apijson): and if <>:/else:
  2. The keywords or/and are case-sensitive so your example AND -> and
  3. Your example json structure has users[0].accesslevel as an array so your (corrected) user_result["accesslevel"] == 'WORKER' won’t evaluate to True since user_result["accesslevel"] = ["WORKER"]

So with some corrections,

def LoadUserList(apijson):
    for user_result in apijson["users"]:
        username = user_result["username"]
        accesslevel = user_result["accesslevel"]
        user_accesslevel = user_access.get(username)  # "WORKER"
        if (username == 'user' and user_accesslevel in accesslevel):
            print("success")
        else:
            print("not matching")
Answered By: ccchoy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.