Fanta Fanta - 1 month ago 17
JSON Question

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

I am trying to encode a dictionary containing a string of bytes with

json
, and getting a
is not JSON serializable error
.

Sample code:

import base64
import json

data={}
encoded = base64.encodebytes(b'data to be encoded')
data['bytes']=encoded

print(json.dumps(data))


The error I receive:

TypeError: b'ZGF0YSB0byBiZSBlbmNvZGVk\n' is not JSON serializable


How can I correctly encode my dictionary containing bytes with JSON?

Answer

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

encoded = base64.encodestring(b'data to be encoded')
data['bytes'] = encoded.decode('ascii')
Comments