TypeError: Object Not JSON Serializable

TypeError: Object of type datetime is not JSON serializable

Quick Answer

You are serializing an object JSON does not support natively, like datetime, set, or bytes. Convert to a supported type or provide a custom encoder.

Why This Happens

JSON only supports strings, numbers, booleans, null, arrays, and objects. Python types like datetime, set, bytes, Decimal must be converted.

The Problem

import json
from datetime import datetime
data = {'timestamp': datetime.now(), 'tags': {1, 2, 3}}
json.dumps(data)

The Fix

import json
from datetime import datetime

class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        if isinstance(obj, set):
            return list(obj)
        return super().default(obj)

json.dumps(data, cls=CustomEncoder)

Step-by-Step Fix

  1. 1

    Convert unsupported types

    Convert datetime to .isoformat(), sets to lists.

  2. 2

    Use default=str

    Pass default=str as a quick fix.

  3. 3

    Write a custom encoder

    Subclass json.JSONEncoder and override default().

Bugsly 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