2

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 ?

bux
  • 7,087
  • 11
  • 45
  • 86
  • Have you tried subclassing your class from `list` or `dict` to achieve what you want? – Alfe Mar 03 '17 at 11:47
  • @Alfe It is working if subclassing `str` etc yes. But i don't want to because my object will cannot completely implement `str` or `list` etc interfaces. – bux Mar 03 '17 at 11:59
  • 1
    Then for json you can have a look at http://stackoverflow.com/questions/3768895/how-to-make-a-class-json-serializable (without creating a private de/encoder it will not be possible from the class itself, but creating that private de/encoder is easy). – Alfe Mar 03 '17 at 12:01
  • For, json you can use [jsonpickle](http://jsonpickle.github.io/#module-jsonpickle) – Kruupös Mar 03 '17 at 12:35

0 Answers0