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
Release: 2024-12-27 04:20:21
Original
716 people have browsed it

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
Copy after login

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
Copy after login

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)
Copy after login

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())
Copy after login

This will output the following JSON:

{
    "age": 35,
    "dog": {
        "name": "Apollo"
    },
    "name": "Onur"
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template