How to encode bytes in JSON? json.dumps() throwing a TypeError How to encode bytes in JSON? json.dumps() throwing a TypeError python-3.x python-3.x

How to encode bytes in JSON? json.dumps() throwing a TypeError


The JSON format only supports unicode strings. Since base64.b64encode encodes bytes to ASCII-only bytes, you can use that codec to decode the data:

import base64encoded = base64.b64encode(b'data to be encoded')  # b'ZGF0YSB0byBiZSBlbmNvZGVk' (notice the "b")data['bytes'] = encoded.decode('ascii')            # 'ZGF0YSB0byBiZSBlbmNvZGVk'

Note that to get the original data back you don't need to re-encode it to bytes because b64decode handles ASCII-only strings as well as bytes:

decoded = base64.b64decode(data['bytes'])  # b'data to be encoded'