Skip to content
Back to Blog
By JSONConvert Team··7 min read

Fix "Not JSON Serializable" Errors in Python

You call json.dumps() on a dict that came out of your database layer and Python stops with TypeError: Object of type datetime is not JSON serializable. The same error shows up for Decimal, UUID, set, bytes, NumPy integers and your own classes. The fix is almost always one argument, but the popular one-liner, default=str, quietly produces JSON you will regret later.

This post covers why the error happens, what each common type should turn into, and a small default function you can reuse. Everything below was run on Python 3.14.

Why json.dumps refuses these types

The json module only knows how to encode a fixed set of Python types. That set maps directly onto what JSON itself can represent:

PythonJSON
dictobject
list, tuplearray
strstring
int, floatnumber
True, Falsetrue, false
Nonenull
Anything else goes to a fallback hook called default. Out of the box that hook just raises TypeError. JSON has no date type, no decimal type and no set type, so Python refuses to guess how you want them written. That is the right call. The encoder can't know whether your Decimal("19.90") is a price that must keep its trailing zero or a measurement where a float is fine.

Here is what fails with the standard library:

Plain Enum members, bytes and pathlib.Path fail the same way. IntEnum and StrEnum members pass because they are real int and str subclasses.

The default=str trap

Search for this error and the top answer is:

It makes the error go away. Look at what it writes, though:

Two of those three values are wrong. The datetime uses a space instead of the T that ISO 8601 expects, so strict parsers such as Go's time.Parse(time.RFC3339, ...) reject it. The set became the string "{1, 2}", which no consumer can parse back into an array. default=str is fine for a debug log line. Don't use it for anything another program reads.

A default function that writes correct JSON

Write the conversions out once and pass the function as default:

With an order containing a UUID, a UTC datetime, an enum, a set of tags and a dataclass with a Decimal price, you get:

A few details worth knowing:

  • default is called again on whatever it returns, so the dict from dataclasses.asdict still gets its Decimal converted.
  • The final raise TypeError matters. If you return None for unknown types, every unexpected object silently becomes null and you lose data without an error.
  • Sets are sorted so the output is stable across runs. Python's set order for strings changes between processes because of hash randomization, which breaks snapshot tests and caching.
  • Decimals go out as strings on purpose. A JSON number gets parsed as a 64-bit float by most consumers, so "19.90" survives and 19.90 may not. See large numbers and precision in JSON for the details.
Paste the output into the JSON validator if you want to confirm a consumer will accept it, or the JSON formatter to read a long payload.

Subclassing JSONEncoder

If you call json.dumps in many places, or a library takes an encoder class instead of a function, wrap the same logic in a JSONEncoder subclass:

One limit catches people out. default only runs for types the encoder does not already handle. You can't use it to change how a float, str or dict subclass is written, because the encoder never asks.

NumPy and pandas values

Data science code hits this error constantly, usually on a value that looks like a normal number:

np.float64 works because it subclasses Python's float. np.int64 does not subclass int, so it fails, and np.bool_ fails with a message that looks like nonsense until you realise it means NumPy's bool. The fix is the same for all of them. Call .tolist() on arrays and .item() on scalars, or add one branch to to_json:

For a pandas DataFrame, skip json.dumps and use df.to_json(orient="records", date_format="iso"), which handles timestamps and NumPy dtypes itself.

Two errors that look similar

Not every serialization failure goes through default.

Dict keys must be str, int, float, bool or None. A tuple key raises TypeError: keys must be str, int, float, bool or None, not tuple, and default is never consulted. Allowed non-string keys are converted silently: {1: "a", None: "b"} becomes {"1": "a", "null": "b"}, so the key types are gone when you load it back.

NaN and infinity are the opposite problem. json.dumps(float("nan")) returns NaN with no error at all, and that output is not valid JSON. JSON.parse in a browser throws on it. Pass allow_nan=False and Python raises ValueError: Out of range float values are not JSON compliant: nan instead, which is what you want in anything that talks to another service.

When to stop writing encoders

A hand-written default is fine for a script. For an application, the libraries below already solve this, and they agree with each other on the formats:

OptiondatetimeDecimalUUIDsetNumPy
json + default=strspace, not ISOstringstringbroken stringfails on arrays
json + to_json aboveISO 8601stringstringsorted arraywith extra branch
Pydantic v2 model_dump_json()ISO 8601, Z for UTCstringstringarrayno
orjson 3.13ISO 8601failsstringnowith OPT_SERIALIZE_NUMPY
Django DjangoJSONEncoderISO 8601stringstringnono
If you already use Pydantic, the cleanest fix is to put the data in a model and call model_dump_json(). Calling model_dump() and passing the dict to json.dumps brings the error straight back, because model_dump() returns real datetime objects. Use model_dump(mode="json") when you need a dict. To get the model in the first place, paste a sample payload into the JSON to Pydantic converter and it writes the classes for you, including Optional fields for keys that are sometimes missing. The Pydantic models from JSON guide goes deeper on that.

orjson is the fast choice and handles datetimes and NumPy natively, but it returns bytes and raises TypeError: Type is not JSON serializable: decimal.Decimal unless you give it a default too.

One last thing to check: whatever format you pick for dates, make it timezone-aware before you serialize. A naive datetime writes as "2026-11-29T09:30:00" with no offset, and every consumer will guess the timezone differently.

Related Tools