HOWTO · Python
How to Serialize a Python Class Object to JSON
This tutorial educates about serialization in Python and demonstrates Python class JSON serialization.
On this page
A custom Python instance cannot be passed directly to the standard json encoder. Convert it to JSON-compatible values first, then use json.dumps() when you need JSON text. To write that text to a file-like object instead, use json.dump().
Serialization in Python
Serialization converts data into a representation that can be stored or transferred and reconstructed later. JSON supports objects, arrays, strings, numbers, booleans, and null; in Python these correspond to dictionaries, lists, strings, numbers, booleans, and None. A custom class instance has no automatic JSON representation, so you must decide which of its attributes to expose and convert them to those supported values.
Make a Python Class JSON Serializable
The JSON encoder handles built-in Python values, including nested dictionaries and lists. For a custom instance, pass a default function to json.dumps() that converts each encountered instance to a dictionary. This works for nested custom objects too, as long as the conversion returns values the encoder can handle.
Use the toJSON() Method to Make a JSON Class Serializable
toJSON() is an ordinary method name chosen by the class author. Python’s json module does not call it automatically. One option is to use the encoder’s default argument and have the method return the JSON text:
Run this example:
import json
class Pet:
def __init__(self, name):
self.name = name
class Person:
def __init__(self, name, age, pet):
self.name = name
self.age = age
self.pet = pet
def toJSON(self):
return json.dumps(self, default=lambda value: value.__dict__, sort_keys=True)
person = Person("Kelvin", 20, Pet("Brunno"))
print(person.toJSON())
This example is provided as runnable code, but no execution result is available for it. Its output has therefore not been verified here. The default callback is applied to both Person and the nested Pet; if an attribute is itself unsupported, add a conversion rule for that value as well.
Wrap JSON Serialization in the Class
A class can also own the conversion step and return a dictionary of JSON-compatible values. Then pass that dictionary to json.dumps(). A dataclass is useful when its fields already describe the data to expose:
from dataclasses import asdict, dataclass
import json
@dataclass
class Student:
id: int
name: str
def toJSON(self):
return asdict(self)
student = Student(id=1, name="Kelvin")
json_text = json.dumps(student.toJSON())
print(json_text)
This example has also not been executed here. asdict() converts the dataclass fields to a dictionary; json.dumps() then returns JSON text. For file output, call json.dump(student.toJSON(), file_object) with an open file-like object instead of printing the returned string. Neither approach makes arbitrary nested Python objects serializable unless those values are also converted.