Fanta Fanta - 1 year ago 157
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

, and getting a
is not JSON serializable error

Sample code:

import base64
import json

encoded = base64.encodebytes(b'data to be encoded')


The error I receive:

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

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

Answer Source

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')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download