Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python: Object of type datetime is not JSON serializable

json.dumps only encodes primitives and containers. Convert datetime, Decimal, UUID, set and NumPy values, or add a default hook that stays strict.

~4 min readPython
#Python#JSON#Serialization#Debugging
A Python object crate rejected at a cyan JSON encoder gate, an amber datetime card and a serializer slot beside it

Introduction & Quick Summary

text
TypeError: Object of type datetime is not JSON serializable

json.dumps knows six types: dict, list, tuple, str, int, float, bool and None. Everything else must be converted before encoding, and the error names the first object it could not handle. The object is usually a datetime, Decimal, UUID, set, bytes, a dataclass or a NumPy scalar.

Three fixes, in increasing scope:

  • Convert at the boundary — datetime.isoformat(), str(uuid), float(decimal).
  • Pass default= — a function called for any unknown object, applied recursively.
  • Subclass JSONEncoder — when the rule must be reused across many call sites.

The choice matters for correctness: default=str makes the error disappear and silently produces values like "Decimal('19.99')" or "<User object at 0x...>", which downstream consumers cannot parse.

Type in the errorCorrect JSON formTrap
datetimeISO 8601 string with offsetNaive datetimes lose timezone
dateYYYY-MM-DDisoformat() on datetime includes time
DecimalString, not floatMoney precision loss
UUIDCanonical hyphenated stringbytes form is not JSON-safe
setList, sorted for determinismOrder changes between runs
bytesBase64 stringDecoding assumptions
numpy.int64Python intisinstance(x, int) is false
dataclassdataclasses.asdictDeep copy of nested values

Core Mechanics, Signatures & Reproducible Setup

The encoder walks containers recursively and calls the C serializer on leaves. On an unknown leaf it raises TypeError unless default is supplied. default is called once per unknown object and its return value is encoded again, so returning a dict is legitimate; returning another unsupported object re-enters the same failure.

Reproduce the common cases:

python
import json from datetime import datetime, timezone from decimal import Decimal from uuid import uuid4 payload = { "id": uuid4(), "created_at": datetime(2026, 11, 23, 10, 0, tzinfo=timezone.utc), "amount": Decimal("19.99"), "tags": {"api", "billing"}, } json.dumps(payload) # TypeError: Object of type UUID is not JSON serializable

Fix explicitly, which keeps every conversion visible in review:

python
def to_jsonable(value): return { "id": str(value["id"]), "created_at": value["created_at"].isoformat(), "amount": str(value["amount"]), "tags": sorted(value["tags"]), } json.dumps(to_jsonable(payload))

Or centralize with a default hook that refuses to guess:

python
def json_default(obj): if isinstance(obj, datetime): if obj.tzinfo is None: raise ValueError("naive datetime: attach a timezone before serializing") return obj.isoformat() if isinstance(obj, Decimal): return str(obj) if isinstance(obj, (set, frozenset)): return sorted(obj) if isinstance(obj, bytes): import base64 return base64.b64encode(obj).decode("ascii") if hasattr(obj, "isoformat"): return obj.isoformat() raise TypeError(f"Unsupported type: {type(obj).__name__}") json.dumps(payload, default=json_default)

Raising on unknown types keeps the contract honest: the next unsupported object fails loudly instead of becoming a string repr.

Key Comparison Table

ApproachCoversReusableRisk
Explicit conversionOnly what you writeNoMissed nested field
default=strEverythingYesUnparseable output
default= functionWhat it handlesYesSilent fallback if too broad
JSONEncoder subclassEverything it handlesYesSame, plus subclassing cost
Pydantic model_dump(mode="json")Model fieldsYesRequires the model
orjson with defaultHandles datetime nativelyYesDifferent library, stricter
dataclasses.asdict + hookDataclassesYesRecurses into all fields
SerializerdatetimeDecimalnumpyNaN allowed
jsonNoNoNoYes, invalid JSON
orjsonYes, UTC-awareNoSomeNo
simplejsonNoYes with use_decimalNoOptional
Pydantic v2YesYes as stringPartialConfigurable

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

Case 1: datetime with and without a timezone

python
from datetime import datetime, timezone datetime.utcnow().isoformat() # '2026-11-23T01:00:00.123456' datetime.now(timezone.utc).isoformat() # '2026-11-23T01:00:00.123456+00:00'

utcnow() returns a naive datetime; its ISO string has no offset, so clients interpret it in local time. Use datetime.now(timezone.utc) and serialize with .isoformat(). On Python 3.11+, datetime.UTC is an alias for timezone.utc.

python
def iso_utc(dt: datetime) -> str: if dt.tzinfo is None: raise ValueError("naive datetime") return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")

The trailing Z is optional; both forms are valid ISO 8601 and JavaScript's Date parses either.

Case 2: Decimal must not become a float

python
from decimal import Decimal import json json.dumps({"total": float(Decimal("0.1") + Decimal("0.2"))}) # {"total": 0.30000000000000004}

For money, serialize as a string and let the consumer use a decimal type:

python
json.dumps({"total": str(Decimal("0.1") + Decimal("0.2"))}) # {"total": "0.3"}

If the consumer requires a number, use orjson with a custom option or round explicitly with a documented scale. Never rely on float(decimal) for currency arithmetic.

Case 3: set ordering changes between processes

python
json.dumps(sorted({"b", "a", "c"})) # ["a", "b", "c"] json.dumps(list({"b", "a", "c"})) # order depends on hashing

Sets of strings are hash-randomized per process unless PYTHONHASHSEED is fixed, so unsorted output makes cached responses and test snapshots unstable. Sort before serializing, or store a list in the first place.

Case 4: dataclasses and nested models

python
from dataclasses import dataclass, asdict, field from datetime import datetime, timezone @dataclass class Event: name: str at: datetime tags: list[str] = field(default_factory=list) e = Event("deploy", datetime.now(timezone.utc), ["api"]) json.dumps(asdict(e), default=str)

asdict recurses into nested dataclasses but leaves datetime untouched, so the default hook is still required. default=str works here but produces a space-separated datetime format instead of ISO 8601 on some types; prefer the explicit hook.

With Pydantic v2, let the model do it:

python
class Event(BaseModel): name: str at: datetime tags: list[str] = [] payload = Event(name="deploy", at=datetime.now(timezone.utc)).model_dump(mode="json") json.dumps(payload)

mode="json" converts datetimes, UUIDs and enums to JSON-safe primitives. model_dump() without it returns Python objects and fails at json.dumps.

Case 5: NumPy and pandas scalars

python
import numpy as np, json json.dumps({"count": np.int64(5)}) # TypeError: Object of type int64 is not JSON serializable

np.int64 is not a subclass of int on all platforms. Convert explicitly:

python
def numpy_default(o): if isinstance(o, np.integer): return int(o) if isinstance(o, np.floating): return float(o) if isinstance(o, np.ndarray): return o.tolist() raise TypeError(type(o).__name__) json.dumps({"count": np.int64(5)}, default=numpy_default)

For DataFrames, df.to_json(orient="records") handles the conversion internally and is less error-prone than serializing df.to_dict().

Case 6: NaN and Infinity produce invalid JSON

python
json.dumps({"value": float("nan")}) # {"value": NaN} <- not valid JSON per RFC 8259

Python's encoder allows these by default. Browsers' JSON.parse rejects the output, and strict parsers in other services fail. Set allow_nan=False to fail at the producer instead of at every consumer:

python
json.dumps(payload, default=json_default, allow_nan=False)

Replace missing numeric values with None before serializing when None is the intended representation.

Common Compilation/Runtime Mistakes & Version Gotchas

  • default=str in production. It converts every unknown type, including objects whose __str__ includes memory addresses, into strings. Bugs move from a loud TypeError to a silent contract violation.
  • Overriding default but not iterencode. A JSONEncoder subclass that changes container handling must override iterencode, not just default; default is only consulted for leaves.
  • Circular references. A self-referencing dict raises ValueError: Circular reference detected, not TypeError. Use check_circular=False only when you know the graph is acyclic.
  • ensure_ascii=True by default. Non-ASCII text is escaped as \uXXXX; output is valid but larger. Set ensure_ascii=False and encode UTF-8 explicitly when writing bytes.
  • Non-string dict keys. int and float keys are coerced to strings; tuples are rejected with TypeError: keys must be str, int, float, bool or None. Convert keys before encoding.
  • Pydantic v1 versus v2. dict() and json() exist in v1; v2 uses model_dump(mode="json"). A v1 tutorial's json.dumps(obj.dict()) fails on v2 models with nested datetimes, which is this error again.

To inspect a failing payload before it is serialized, format it with the JSON formatter. When the data arrived as CSV, the CSV to JSON converter shows which columns became strings and which stayed unquoted, which explains many Decimal and int mismatches at the source.

Primary references: json documents default, allow_nan and the encoder protocol, and datetime.isoformat defines the string form including the offset.

Official references

primary documentation

The Python documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.