I am making an ajax call to another service in which they ask me to pass some values through MD5 to send them to them. I perform the hash with the haslib library and get a hash object. My problem is that when passing it through ajax it gives me the following error:
b'\xb8\xadE\xdc\xb98\x1a\xa9|\xe7\\x17\x8dD\xaal' is not JSON serializable
My code is this:
session = request.COOKIES['sessionid']+str(datetime.now().microsecond)
hash = hashlib.md5(session.encode('utf-8')).digest()
The error can be reproduced if you try to convert that hash to json, for example like this:
resultado = json.dumps({"md5": hash})
The method
digest
returns the hash as a sequence of bytes. The following code shows a simple example that can be run from a standard interpreter, without the need for django or the rest of your application:It will show something like:
This is python3's way of representing a sequence of bytes. The
b
initial indicates that it is not a normal string, but of bytes. Inside it may appear bytes that are decoded as ASCII (such as theT
initial one) and others that would not be valid ASCII (such as the\x95
one below, which represents a hexadecimal value byte95
).These types of binary strings cannot be converted to JSON, since JSON allows only strings with valid UNICODE characters.
The usual thing when you want to send a hash as JSON is to use its hexadecimal representation, which would be an ASCII string containing only the characters
0
--9
anda
--f
.The module
hashlib
can produce such a string for you with thehexdigest()
. For example:Sample:
Note that now the result is already a normal string and everything in it is ascii characters, but somehow it represents the same information since the
54
initial one is the ASCII of theT
, the95
next one would be the byte\x95
, etc.Now you will have no problem serializing it as json:
And it would output: