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
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}
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__)
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"}
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!