I have a Python dictionary where the keys are strings, and values are list of MyObject objects. If I execute
simplejson.dumps(dict)
it throws "MyObject not JSON serializable".
How can I avoid this exception, and how can I make MyObject serializable?
Proper Answer
In order to make your
MyObject
serializable, you need to implement a method that you can reference ondumps
. For example:The cool thing is that
dumps
will, like every other JSON-serializable object, call the serialization method recursively. That is,obj.parent
will get serialized as well, without any further action from you.Golf'd Version
If all you want to do is 1-1 map instance variable names to their respective values, you can use some built-in Python magic. Whenever you want to serialize a more complex object (again, only using a 1-1 variable-value map), just call this line:
For the given instance of
MyObject
, it will behave identically to the aforementionedserialize
method.