Why This Happens
JSON has no binary type. Bytes must be converted to strings: decode UTF-8 for text, or base64-encode for binary data.
The Problem
import json
data = {'content': b'Hello World'}
json.dumps(data)The Fix
import json, base64
# For text:
data = {'content': b'Hello World'.decode('utf-8')}
# For binary:
binary = b'\x89PNG\r\n'
data = {'image': base64.b64encode(binary).decode('ascii')}
json.dumps(data)
# Or let one encoder handle bytes everywhere:
class BytesEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, bytes):
return base64.b64encode(o).decode('ascii')
return super().default(o)
json.dumps({'image': binary}, cls=BytesEncoder)Step-by-Step Fix
- 1
Decode text bytes
Use .decode('utf-8').
- 2
Base64 encode binary
Use base64.b64encode(data).decode('ascii').
- 3
Use a custom encoder
Write a JSONEncoder that handles bytes.
Got the actual stack trace?
Paste it into our free AI explainer to get the cause and the fix for your specific case — no signup, nothing to install.
Explain my errorBugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free