Home >Backend Development >Python Tutorial >How Can I Serialize Custom Python Classes to JSON?

How Can I Serialize Custom Python Classes to JSON?

Barbara Streisand
Barbara StreisandOriginal
2024-12-27 04:20:21713browse

How Can I Serialize Custom Python Classes to JSON?

Serializing Custom Python Classes to JSON

Problem

Python classes cannot natively be serialized to JSON. Consider the following class:

class FileItem:
    def __init__(self, fname):
        self.fname = fname

This class cannot be directly serialized to JSON:

>>> import json
>>> x = FileItem('/foo/bar')
>>> json.dumps(x)
TypeError: Object of type 'FileItem' is not JSON serializable

Solution

To resolve this issue, one approach is to implement a serializer method:

toJSON() Method

import json

class Object:
    def toJSON(self):
        return json.dumps(
            self,
            default=lambda o: o.__dict__, 
            sort_keys=True,
            indent=4)

With this method in place, you can serialize the class:

me = Object()
me.name = "Onur"
me.age = 35
me.dog = Object()
me.dog.name = "Apollo"

print(me.toJSON())

This will output the following JSON:

{
    "age": 35,
    "dog": {
        "name": "Apollo"
    },
    "name": "Onur"
}

Additional Library

For a more comprehensive solution, you can utilize the orjson library.

The above is the detailed content of How Can I Serialize Custom Python Classes to JSON?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn