Open In App

Convert class object to JSON in Python

Last Updated : 02 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, class objects are used to organize complex information. To save or share this information, we need to convert it into a format like JSON, which is easy to read and write. Since class objects can’t be saved directly as JSON, we first convert them into a dictionary (a data structure with key-value pairs). Once in this format, the object can easily be turned into JSON. Let’s explore different methods to achieve this.

Using json.dumps() with __dict__

Every Python object has a __dict__ attribute that stores its attributes in a dictionary form. By accessing this attribute, you can quickly convert the object’s data into a dictionary, which can then be serialized into a JSON string using json.dumps(). This method works well for simple objects but doesn’t give you control over how the object is represented in JSON.

Python
import json

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

p1 = Person("Alice", 30)

# Convert object's attributes (__dict__) to JSON
res = json.dumps(p1.__dict__)
print(res)

Output
{"name": "Alice", "age": 30}

Explanation: json.dumps(p1.__dict__) line converts the object’s __dict__ attribute, which holds the instance’s attributes as a dictionary, into a JSON string.

Using to_dict()

Defining a to_dict() method within the class gives you more control over how the object is serialized. This method can return a custom dictionary representation of the object, allowing you to exclude certain attributes, rename them, or transform the data before serialization.

Python
import json

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

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

p1 = Person("Alice", 30)
res = json.dumps(p1.to_dict())  # Use to_dict() to serialize
print(res)

Output
{"name": "Alice", "age": 30}

Explanation: json.dumps(p1.to_dict()) calls the to_dict() method of the Person class, which returns a dictionary representation of the object’s attributes. This dictionary is then serialized into a JSON string using json.dumps().

Using dataclasses with asdict()

Python’s dataclasses module provides a simple way to define classes with minimal boilerplate. The asdict() function converts a dataclass instance into a dictionary, which can then be easily serialized into JSON. This method is ideal for immutable objects and works seamlessly with dataclass fields.

Python
import json
from dataclasses import dataclass, asdict

@dataclass
class Person:
    name: str
    age: int

p1 = Person("Alice", 30)
res = json.dumps(asdict(p1))  # Convert to dictionary and then JSON
print(res)

Output
{"name": "Alice", "age": 30}

Explanation: json.dumps(asdict(p1)) uses the asdict() function from the dataclasses module to convert the Person dataclass instance into a dictionary. This dictionary representation of the object is then serialized into a JSON string using json.dumps().

Using __json__ method

For more complex serialization needs, you can implement a __json__() method in your class. This method returns a custom dictionary representation of the object when called. By passing a lambda function to the default parameter of json.dumps(), you can ensure that the __json__() method is invoked during serialization, allowing full control over the object’s JSON output.

Python
import json

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

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

p1 = Person("Alice", 30)
res = json.dumps(p1, default=lambda o: o.__json__() if hasattr(o, '__json__') else None)
print(res)

Output
{"name": "Alice", "age": 30}

Explanation: json.dumps() uses the __json__() method for custom serialization, converting the object to a dictionary if it exist and then serializing it to JSON. The default parameter applies this only to objects with the __json__() method.



Next Article
Practice Tags :

Similar Reads