Serializing Complex Python Objects to JSON with Custom Encoders
Use default or a JSONEncoder subclass to convert unsupported Python values into an explicit JSON representation. An unhandled TypeError stops the whole dump. Add object_hook only when you need to reconstruct custom types from marker objects.
On this page
The short answer
The standard json encoder handles built-in JSON-compatible values. A default function or JSONEncoder subclass can convert an unsupported value, such as a complex number or custom class, into a supported value. If it raises TypeError for an unhandled value, the current dumps call fails; encoding does not continue past that object. object_hook is optional and is useful only when your application chooses to rebuild custom types from an explicit marker structure.
Why JSON Does Not Serialize Arbitrary Python Objects
The json module defines a fixed conversion table. Python dict maps to a JSON object, list and tuple map to an array, str maps to a string, int and float map to a number, True and False map to their JSON literals, and None maps to null. Complex numbers, datetime instances, pathlib.Path objects, and user-defined class instances have no entry in this table. When the encoder encounters a value outside the table it calls the default hook. If no hook is provided the default hook raises TypeError. The documentation states this explicitly: the encoder supports only the listed types and to extend it you must subclass JSONEncoder and implement a default method.
import json
# This raises TypeError because complex has no default mapping
try:
json.dumps(1 + 2j)
except TypeError as e:
print(e)Practical tip
Choose a representation first. If a custom object becomes an ordinary string or dictionary and that form is sufficient, no custom decoder is needed. If you must reconstruct a Python type, use a distinctive marker, validate its fields, and implement a matching object_hook. Do not treat arbitrary incoming marker dictionaries as trusted objects.
Serialization via the default Parameter in json.dumps
The default parameter receives an unsupported value and must return a JSON-compatible value, such as a string or dictionary. If the function cannot handle that value, raising TypeError aborts the current json.dumps call. It does not skip the value or continue serializing the rest of the document. One callback can handle several known types and raise only for values it truly cannot represent.
The source documentation shows the canonical example with complex numbers: a function checks isinstance(obj, complex), returns a marker dictionary with real and imag fields, and raises TypeError for everything else.
import json
def custom_json(obj):
if isinstance(obj, complex):
return {"__complex__": True, "real": obj.real, "imag": obj.imag}
raise TypeError(f"Cannot serialize object of {type(obj)}")
print(json.dumps(1 + 2j, default=custom_json))Extending Behavior Through a JSONEncoder Subclass
When the same serialization logic must be reused across multiple call sites or when you need to configure encoder-level parameters such as indent or ensure_ascii together with custom type handling, subclassing JSONEncoder is the cleaner option. You override the default method and call super().default(o) for unhandled types so that the standard TypeError is raised with the library's own message. The subclass is passed to json.dumps or json.dump through the cls parameter.
This pattern separates the encoding policy from the call site. Any consumer that imports your encoder class gets consistent behavior without duplicating the isinstance chain.
import json
class SimpleEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, complex):
return {"__complex__": True, "real": o.real, "imag": o.imag}
return super().default(o)
print(json.dumps({"z": 3 + 4j}, cls=SimpleEncoder))Choosing Between a default Function and a JSONEncoder Subclass
Use a plain default function when the transformation is specific to one call, the logic is short, and you do not need to share encoder configuration. The function is passed inline and disappears after the call. Use a JSONEncoder subclass when the logic must be reused, when you want to combine custom type handling with non-default encoder settings such as sort_keys or a custom separators tuple, or when the transformation chain grows beyond two or three isinstance checks and a flat function becomes hard to read.
A practical threshold: if you find yourself passing the same default function to dumps in more than two places, promote it to a class. If the class only overrides default and adds no constructor parameters, the function form is still acceptable.
import json
from datetime import datetime, timezone
class ProjectEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, datetime):
return o.isoformat()
if isinstance(o, complex):
return {"__complex__": True, "real": o.real, "imag": o.imag}
return super().default(o)
payload = {"ts": datetime(2024, 1, 15, tzinfo=timezone.utc), "z": 1+1j}
print(json.dumps(payload, cls=ProjectEncoder, sort_keys=True))Encoding Dates, Paths, and User-Defined Classes
datetime and Path values can be represented as strings. A custom class can be represented by a dictionary containing a type marker and the fields the application needs. Add object_hook only if decoding should turn that marker dictionary back into a Python object. If a plain dictionary is an acceptable result, leave it as a dictionary and no hook is required.
import json
from datetime import datetime, timezone
from pathlib import Path
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def encode(obj):
if isinstance(obj, datetime):
return obj.isoformat()
if isinstance(obj, Path):
return str(obj)
if isinstance(obj, Point):
return {"__type__": "Point", "x": obj.x, "y": obj.y}
raise TypeError(f"Unsupported type {type(obj)}")
def decode(dct):
if dct.get("__type__") == "Point":
return Point(dct["x"], dct["y"])
return dct
p = Point(3, 4)
s = json.dumps(p, default=encode)
print(s)
restored = json.loads(s, object_hook=decode)
print(type(restored).__name__, restored.x, restored.y)Encoder Parameters That Affect Output
ensure_ascii controls whether non-ASCII characters are escaped; indent and separators change whitespace; sort_keys orders object keys. allow_nan=False rejects NaN and infinity. With skipkeys=False, unsupported dictionary keys such as tuples raise TypeError. Integer, float, boolean, and None keys are accepted and become strings in JSON object names. Setting skipkeys=True silently omits unsupported keys, so it should be a deliberate data-loss policy.
import json
from datetime import datetime
class Enc(json.JSONEncoder):
def default(self, o):
if isinstance(o, datetime):
return o.isoformat()
return super().default(o)
print(json.dumps({"b": 1, "a": datetime(2024,1,1)}, cls=Enc, sort_keys=True, indent=2))Error Handling and Portability Limitations
When default or the encoder's default method raises TypeError the entire dumps call fails; there is no partial output. This means one unsupported object anywhere in the tree aborts the whole serialization. Design your default function to raise TypeError with a clear message naming the offending type so that debugging is fast.
Repeated json.dump calls to the same file append separate JSON texts without framing, so the combined file is not one valid JSON document. Integer, float, boolean, and None keys may become strings, while tuple keys are unsupported by default and raise TypeError unless skipkeys=True omits them. Consumers that parse JSON numbers as binary floating point may not preserve every large integer or decimal value.
Source excerpt: 'Unlike pickle and marshal, JSON is not a framed protocol, so trying to serialize multiple objects with repeated calls to dump() using the same fp will result in an invalid JSON file.'
import json, io
buf = io.StringIO()
json.dump({"a": 1}, buf)
json.dump({"b": 2}, buf) # second call makes the file invalid
print(buf.getvalue()) # {"a": 1}{"b": 2} - not valid JSONPractical Example Combining Complex Numbers and a Custom Class
This example encodes a complex number and a custom Event as marker dictionaries. The output remains ordinary JSON objects. object_hook is included because this example explicitly reconstructs those Python types; omit it if the dictionaries themselves are the desired output.
This example runs on Python 3.6 and later. It requires no third-party packages. The only prerequisite is familiarity with isinstance, dictionaries, and the json module's basic API.
import json
class Event:
def __init__(self, name, ts, payload):
self.name = name
self.ts = ts
self.payload = payload
# Approach 1: standalone default function
def complex_default(obj):
if isinstance(obj, complex):
return {"__complex__": True, "real": obj.real, "imag": obj.imag}
raise TypeError(f"Cannot serialize {type(obj)}")
s1 = json.dumps(1 + 2j, default=complex_default)
print(s1)
# Approach 2: reusable JSONEncoder subclass
class AppEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, complex):
return {"__complex__": True, "real": o.real, "imag": o.imag}
if isinstance(o, Event):
return {"__type__": "Event", "name": o.name,
"ts": o.ts, "payload": o.payload}
return super().default(o)
s2 = json.dumps({"z": 3+4j, "ev": Event("click", 100, {"x": 1})},
cls=AppEncoder, sort_keys=True)
print(s2)
# Round-trip decode
def app_hook(dct):
if dct.get("__complex__"):
return complex(dct["real"], dct["imag"])
if dct.get("__type__") == "Event":
return Event(dct["name"], dct["ts"], dct["payload"])
return dct
restored = json.loads(s2, object_hook=app_hook)
print(type(restored["z"]).__name__, restored["ev"].name)Things to check
- Without default or cls, unsupported values such as complex and custom instances raise TypeError.
- A default function must return a JSON-compatible value or raise TypeError; an exception stops the current dumps call.
- Use object_hook only when the chosen marker format must be reconstructed as a custom type.
- Integer, float, boolean, and None keys may become strings; tuple keys raise TypeError unless skipkeys=True, which skips them.
- Repeated json.dump calls on one file object concatenate documents and do not create a valid JSON sequence.
- ensure_ascii and formatting parameters affect representation; allow_nan=False rejects non-finite floats.
- Limit size and resource use when decoding untrusted input.
Where this applies
This article covers the standard library json module. The default hook converts values during encoding but does not create a typed JSON value. object_hook is an application-defined reconstruction step, not a general schema or type registry. Integer, float, boolean, and None dictionary keys may become strings; tuple keys are unsupported by default and are skipped only when skipkeys=True. Consumers that parse numbers as binary floating point may lose precision for large integers or decimal values.