python serialization_error ai_generated true

TypeError: Object of type X is not JSON serializable

ID: python/typeerror-not-json-serializable

Also available as: JSON · Markdown
95%Fix Rate
95%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
311 active

Root Cause

json.dumps can't serialize the object. Common: datetime, set, numpy, Decimal, UUID.

generic

Workarounds

  1. 92% success Write a custom encoder: class CustomEncoder(json.JSONEncoder)
    class CustomEncoder(json.JSONEncoder):
        def default(self, o):
            if isinstance(o, datetime): return o.isoformat()
            if isinstance(o, set): return list(o)
            return super().default(o)

    Sources: https://docs.python.org/3/library/json.html#json.JSONEncoder

  2. 90% success Convert the specific type before serializing: list(set), str(uuid)
    list(set), str(uuid)

    Sources: https://docs.python.org/3/library/json.html

Dead Ends

Common approaches that don't work:

  1. Use str() on everything before serializing 60% fail

    Loses type information — can't deserialize back correctly

  2. Use pickle instead of JSON 75% fail

    Pickle is Python-only, insecure, and not human-readable

Error Chain

Frequently confused with: