How to make a Python class serializable?
class FileItem:
def __init__(self, fname):
self.fname = fname
Attempt to serialize to JSON:
>>> import json
>>> x = FileItem('/foo/bar')
>>> json.dumps(x)
TypeError: Object of type 'FileItem' is not JSON serializable
Do you have an idea about the expected output? For example, will this do?
In that case you can merely call
json.dumps(f.__dict__).If you want more customized output then you will have to subclass
JSONEncoderand implement your own custom serialization.For a trivial example, see below.
Then you pass this class into the
json.dumps()method asclskwarg:If you also want to decode then you’ll have to supply a custom
object_hookto theJSONDecoderclass. For example: