Home > Backend Development > Python Tutorial > How to Make a Python Class JSON Serializable?

How to Make a Python Class JSON Serializable?

DDD
Release: 2024-12-19 18:09:08
Original
146 people have browsed it

How to Make a Python Class JSON Serializable?

How to Make a Python Class JSON Serializable

Serialization is the process of converting an object into a format that can be stored or transmitted. JSON (JavaScript Object Notation) is a popular data format used for transmitting data between applications.

To serialize a Python class to JSON, you need to implement the dict special method. dict returns a dictionary that contains the attributes of the object. You can then use the json.dumps() function to serialize the dictionary to JSON.

For example:

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

To serialize the FileItem class to JSON, you can implement the dict special method as follows:

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

    def __dict__(self):
        return {'fname': self.fname}
Copy after login

You can then use the json.dumps() function to serialize the FileItem object to JSON:

import json

x = FileItem('/foo/bar')
json_data = json.dumps(x, default=lambda o: o.__dict__)
Copy after login

The default=lambda o: o.__dict__ argument is required because the FileItem class is not natively JSON serializable. This argument tells the json.dumps() function to call the dict method of the object before serializing it.

The resulting JSON data will be:

{"fname": "/foo/bar"}
Copy after login

The above is the detailed content of How to Make a Python Class JSON Serializable?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template