How to make an object serializable ? The following code:
# -*- coding: utf-8 -*-
import json
import pickle
import bson
class A(object):
def __init__(self):
self.a = 'a'
def __reduce__(self):
return type(self), (self.a,)
try:
print(pickle.dumps({'a': A()})) # Ok
except Exception as exc:
print(exc)
try:
print(json.dumps({'a': A()})) # Error
except Exception as exc:
print(exc)
try:
print(bson.BSON.encode({'a': A()})) # Error
except Exception as exc:
print(exc)
produce:
b'\x80\x03}q\x00X\x01\x00\x00\x00aq\x01c__main__\nA\nq\x02h\x01\x85q\x03Rq\x04s.'
<__main__.A object at 0x7f3a06fef048> is not JSON serializable
Cannot encode object: <__main__.A object at 0x7f3a06fef048>
I don't want to write my own JSON, BSON, etc serializer, i need to make object json/bson/... serializable by itself.
Is it possible ? How ?