Corgs Corgs - 26 days ago 5x
JSON Question

Function returning false when it should be returning True. Encoding issue?

I am currently working on a validation function that returns

based on an expression (if statement). The header is base64 decoded and then
is used to convert it into a dict. Here is the method:

def verify(rel):
if not('hello' in rel and rel['hello'] is 'blah' and 'alg' in rel and rel['alg'] is 'HS256'):
return False
return True

The check only fails if the parameter was base 64 decoded and converted to a dict. Why? Any help would be appreciated.

Edit: As per request, here Is how I call the method. Python 3.5.2

p = {'hello': 'blah', 'alg': 'HS256'}
f = urlsafe_b64encode(json.dumps(p).encode('utf-8'))
h = json.loads(str(urlsafe_b64decode(f))[2:-1], 'utf-8')


The issue here is your use of the is operator to check the equality of the strings. The is operator checks if its two arguments refer to the same object, which is not the behavior you want here. To check if the strings are equal, use the equality operator:

 def verify(rel):
    if not('hello' in rel and rel['hello'] == 'blah' and 'alg' in rel and rel['alg'] == 'HS256'):
        return False
    return True