Skip to content

How to make a class JSON serializable

To make a class JSON serializable in Python, you typically define a to_json method that returns a dictionary representation of the object. The __init__ method is not required for serialization; it is simply the standard class constructor used to initialize attributes.

Here is an example of a basic class that is JSON serializable:

JSON serializing a Python class using json module

python
import json

class MyClass:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def to_json(self):
        return {
            'name': self.name,
            'age': self.age
        }

# Create an instance of the class
obj = MyClass('John', 30)

# Convert the object to a JSON string
json_str = json.dumps(obj.to_json())

# Print the JSON string
print(json_str)

In this example, to_json returns a dictionary that has keys 'name' and 'age' and values that are the attributes of the object. The json.dumps() function is then used to convert the dictionary to a JSON string. For simpler cases, you can also serialize an object directly using json.dumps(obj.__dict__), or create a custom json.JSONEncoder subclass for more complex objects.

You can also use the jsonpickle library to simplify the process. First, install it via pip:

bash
pip install jsonpickle

JSON serializing a Python class using jsonpickle module

python
import jsonpickle

class MyClass:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Create an instance of the class
obj = MyClass('John', 30)

# Convert the object to a JSON string
json_str = jsonpickle.encode(obj)

# Print the JSON string
print(json_str)

With this approach, you do not need to define a to_json method, as jsonpickle automatically converts the class instance to JSON.

Dual-run preview — compare with live Symfony routes.