Home >Backend Development >Python Tutorial >How Can I Serialize Custom Python Classes to JSON?
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
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!