How to make a Python class serializable?
A simple class:
class FileItem:
def __init__(self, fname):
self.fname = fname
What should I do to be able to get output of:
json.dumps()
Without an error (FileItem instance at ... is not JSON serializable
)
Another option is to wrap JSON dumping in its own class:
Or, even better, subclassing FileItem class from a
JsonSerializable
class:Testing:
Here is a simple solution for a simple feature:
.toJSON()
MethodInstead of a JSON serializable class, implement a serializer method:
So you just call it to serialize:
will output:
This class can do the trick, it converts object to standard json .
usage:
working in
python2.7
andpython3
.If you are able to install a package, I'd recommend trying dill, which worked just fine for my project. A nice thing about this package is that it has the same interface as
pickle
, so if you have already been usingpickle
in your project you can simply substitute indill
and see if the script runs, without changing any code. So it is a very cheap solution to try!(Full anti-disclosure: I am in no way affiliated with and have never contributed to the dill project.)
Install the package:
Then edit your code to import
dill
instead ofpickle
:Run your script and see if it works. (If it does you may want to clean up your code so that you are no longer shadowing the
pickle
module name!)Some specifics on datatypes that
dill
can and cannot serialize, from the project page:Just add
to_json
method to your class like this:And add this code (from this answer), to somewhere at the top of everything:
This will monkey-patch json module when it's imported so JSONEncoder.default() automatically checks for a special "to_json()" method and uses it to encode the object if found.
Just like Onur said, but this time you don't have to update every
json.dumps()
in your project.if use standard
json
, u need to define adefault
function