How to encode bytes in JSON? json.dumps() throwing a TypeError
<p>I am trying to encode a dictionary containing a string of bytes with <code>json</code>, and getting a <code>is not JSON serializable error</code>.</p>

<p>Sample code:</p>

<pre><code>import base64
import json

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

print(json.dumps(data))
</code></pre>

<p>The error I receive:</p>

<pre class="lang-none prettyprint-override"><code>TypeError: b'ZGF0YSB0byBiZSBlbmNvZGVk\n' is not JSON serializable
</code></pre>

<p>How can I correctly encode my dictionary containing bytes with JSON?</p>

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

<pre><code>encoded = base64.encodestring(b'data to be encoded')
data['bytes'] = encoded.decode('ascii')
</code></pre>

python json python-3.x