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
)
I liked Lost Koder's method the most. I ran into issues when trying to serialize more complex objects whos members/methods aren't serializable. Here's my implementation that works on more objects:
I came across this problem the other day and implemented a more general version of an Encoder for Python objects that can handle nested objects and inherited fields:
Example:
Result:
Do you have an idea about the expected output? For e.g. 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
JSONEncoder
and implement your own custom serialization.For a trivial example, see below.
Then you pass this class into the
json.dumps()
method ascls
kwarg:If you also want to decode then you'll have to supply a custom
object_hook
to theJSONDecoder
class. For e.g.I came up with my own solution. Use this method, pass any document (dict,list, ObjectId etc) to serialize.
json
is limited in terms of objects it can print, andjsonpickle
(you may need apip install jsonpickle
) is limited in terms it can't indent text. If you would like to inspect the contents of an objecth whose class you can't change, I still couldn't find a straighter way than:Note that still they can't print the object methods.
If you're using Python3.5+, you could use
jsons
. It will convert your object (and all its attributes recursively) to a dict.Or if you wanted a string:
Or if your class implemented
jsons.JsonSerializable
: