What the Error Means
JSON only knows strings, numbers, booleans, null, arrays and objects. json.dumps()converts Python's dict, list, tuple, str, int, float, bool and None automatically. Anything else stops it:
TypeError: Object of type datetime is not JSON serializable
The type name in the message tells you which value to fix. Recent Python versions also add notes that show where the value is. For {'order': {'when': datetime(...)}} Python 3.14 printed:
TypeError: Object of type datetime is not JSON serializable when serializing dict item 'when' when serializing dict item 'order'
Which Types Fail
We passed each of these to json.dumps() on Python 3.14:
| Value | Error says | Good JSON form |
|---|---|---|
datetime, date | datetime, date | ISO string: value.isoformat() |
Decimal | Decimal | str(value) to keep every digit, or float(value) |
set, frozenset | set | A list: sorted(value) or list(value) |
UUID | UUID | str(value) |
bytes | bytes | Base64 text, or value.decode("utf-8") if it is text |
| A dataclass | the class name, e.g. Point | dataclasses.asdict(value) |
| Your own class | the class name, e.g. User | vars(value) or a to_dict() method |
Enum | the enum name, e.g. Color | value.value |
pathlib.Path | WindowsPath / PosixPath | str(value) |
A tuple does work: it becomes a JSON array. NumPy values fail the same way with the NumPy type name (such as int64 or ndarray); convert them with .item() or .tolist() first.
The Quick Fix: default=str (and Its Catch)
default is a function json.dumps calls for every value it cannot handle. Passing str makes the error go away:
json.dumps(order, default=str)
But look at what it produced for a UUID, a datetime, a Decimal and a set:
{"id": "12345678-1234-5678-1234-567812345678", "created": "2026-11-20 09:30:00",
"total": "19.99", "tags": "{'new'}"}The date has a space instead of the ISO T, which many APIs and JavaScript's Date do not accept reliably, and the set became the useless string "{'new'}" instead of a list. Fine for logging; not for data other programs read.
The Right Fix: Your Own default Function
import dataclasses, datetime, decimal, enum, json, uuid
def to_json(value):
if isinstance(value, (datetime.datetime, datetime.date)):
return value.isoformat()
if isinstance(value, decimal.Decimal):
return str(value)
if isinstance(value, (set, frozenset)):
return sorted(value)
if isinstance(value, uuid.UUID):
return str(value)
if dataclasses.is_dataclass(value):
return dataclasses.asdict(value)
if isinstance(value, enum.Enum):
return value.value
raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable")
json.dumps(order, default=to_json){"id": "12345678-1234-5678-1234-567812345678", "created": "2026-11-20T09:30:00",
"total": "19.99", "tags": ["new"]}The last line matters: types you did not plan for still raise an error instead of being silently turned into strings. The ISO dates read back exactly with datetime.fromisoformat().
Reusable: Subclass JSONEncoder
If many places in your code write JSON, put the rules in one encoder class:
class AppEncoder(json.JSONEncoder):
def default(self, value):
if isinstance(value, (datetime.datetime, datetime.date)):
return value.isoformat()
return super().default(value) # raises the normal TypeError
json.dumps({"when": datetime.date(2026, 11, 20)}, cls=AppEncoder)
# {"when": "2026-11-20"}default= and cls= work the same with json.dump() when writing a file.
Your Own Classes and Dataclasses
from dataclasses import dataclass, asdict
@dataclass
class Point:
x: int
y: int
json.dumps(asdict(Point(1, 2))) # {"x": 1, "y": 2}
class User:
def __init__(self, name, email):
self.name, self.email = name, email
json.dumps(vars(User("Emily", "emily@example.com")))
# {"name": "Emily", "email": "emily@example.com"}vars() returns the object's attributes, including any you might not want to share, such as passwords or internal caches. For anything sent to a client, write an explicit to_dict() method that lists the fields. For larger projects, Pydantic models have model_dump_json(), and the JSON to Python tool can generate dataclasses or Pydantic models from example JSON.
Frameworks
- Flask's
jsonify()converts Decimal, UUID and dataclasses, and dates too, but as HTTP date strings (Fri, 20 Nov 2026 09:30:00 GMT), not ISO. Your own classes still need ato_dict(). - Django has
DjangoJSONEncoderfor dates, Decimal and UUID:json.dumps(data, cls=DjangoJSONEncoder). - FastAPI converts Pydantic models, dates and UUIDs in responses automatically.
Frequently Asked Questions
What does Object of type datetime is not JSON serializable mean?
json.dumps() only converts dicts, lists, tuples, strings, numbers, booleans and None. A datetime is none of these, so it stops. Convert it to an ISO string with value.isoformat(), or pass a default= function that does it.
Is default=str a good fix?
It removes the error but is not ideal for data: dates become strings with a space instead of the ISO T, and a set becomes text like "{'new'}" instead of a list. Write a small default function that converts each type properly.
How do I serialize a Decimal to JSON?
Use str(value) to keep every digit exactly, or float(value) if a JSON number is required and small rounding errors are acceptable. Handle it in a default= function or a JSONEncoder subclass.
How do I convert my own class or dataclass to JSON?
For a dataclass use json.dumps(dataclasses.asdict(obj)). For other classes add a to_dict() method that returns the fields you want to share, or use vars(obj) if every attribute is safe to include.