"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Make My Python Classes JSON Serializable?

How Can I Make My Python Classes JSON Serializable?

Published on 2024-12-21
Browse:216

How Can I Make My Python Classes JSON Serializable?

Making Python Classes JSON Serializable

Serialization allows objects to be converted into a format suitable for persistence or transfer. Serializing custom classes in JSON often results in a TypeError due to their non-JSON-serializable nature.

Implementing a toJSON() Method

One approach is to create a toJSON() method for the class, which manually handles its serialization. This requires implementing a custom JSON serialization function and ensuring proper handling of nested objects.

import json

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

    def toJSON(self):
        return json.dumps(self.__dict__)

x = FileItem('/foo/bar')
print(x.toJSON())  # Outputs: '{"fname": "/foo/bar"}'

Using the orjson Library

For a comprehensive solution, consider using the orjson library, which provides an efficient and customizable way to serialize custom classes to JSON. It offers advanced features like schema enforcement and support for complex object structures.

import orjson

@orjson.dataclass
class FileItem:
    fname: str

x = FileItem('/foo/bar')
json_bytes = orjson.dumps(x)  # Returns a byte string
print(json_bytes.decode())  # Outputs: '{"fname": "/foo/bar"}'

Conclusion

Using a custom toJSON() method or the orjson library provides convenient solutions for serializing Python classes to JSON. Both approaches ensure that objects can be effectively represented and transmitted in a JSON format.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3