Serializing class instance to JSON
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
JSON can represent strings, numbers, booleans, arrays, and objects, but it does not know how to serialize an arbitrary class instance by itself. When you serialize a custom object, the real job is converting it into JSON-compatible data first. In Python, that usually means turning the instance into a dictionary or supplying a custom encoder.
Why Custom Objects Fail by Default
The standard json module only understands built-in JSON-compatible types. If you pass a custom instance directly, you get a TypeError.
That happens because JSON needs a data structure such as a dictionary, not an opaque Python object with methods and identity.
The Simplest Case: Use __dict__
If the class only contains JSON-safe attributes, serializing __dict__ is often enough.
This is fine for simple objects, but it becomes too blunt when the object contains nested custom classes, dates, or internal fields you do not want to expose.
Use default for Explicit Conversion
A cleaner pattern is to pass a conversion function through the default parameter of json.dumps.
This keeps the JSON representation intentional. You can rename fields, omit sensitive values, or normalize nested content.
Dataclasses Make This Easier
If the class is mainly data, dataclasses are a natural fit. asdict converts the instance into a serializable structure.
This is often the cleanest option when you control the class definition and the object is essentially a data container.
Nested Objects and Non-JSON Types
Real objects often contain values such as datetime, Decimal, or nested custom instances. Those still need explicit conversion.
The important idea is that JSON serialization is about projecting object state into portable data, not about serializing Python behavior.
Let the Class Define Its Public Shape
Another strong pattern is giving the class a method such as to_dict():
This works well when the class itself should own the mapping between internal state and public JSON representation.
Common Pitfalls
The biggest mistake is assuming json.dumps can serialize arbitrary class instances automatically. It cannot unless you first convert them into JSON-compatible data.
Another issue is dumping __dict__ blindly and exposing internal or sensitive attributes that should not appear in JSON.
People also forget nested or special types. One datetime or child object is enough to break a naive serialization path.
Finally, do not confuse JSON serialization with object persistence. JSON is a data interchange format, not a full capture of Python object behavior.
Summary
- Serializing a class instance to JSON means converting it into JSON-compatible data first.
- '
__dict__works for simple cases but is often too blunt for real applications.' - '
defaultinjson.dumpsgives you explicit control over conversion.' - Dataclasses combine naturally with
asdictfor data-oriented objects. - Be deliberate about nested objects, non-JSON types, and which attributes should be exposed.
Related reading
- Session graph is empty
- Set Collection - Insert multiple elements
- Set Cover or Hitting Set; Numpy, Least element combinations to make up full set
- Set inputType for an EditText Programmatically?
- Set markers for individual points on a line
- Set Matplotlib colorbar size to match graph
- set_model missing 1 required positional argument 'model
- Set of List of sets Cartesian products from graph corresponding to set of lists

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.