Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can't serialize arbitrary objects with <code>simplejson</code>. You need to pass a <code>default</code> and <code>object_hook</code> to <code>dump</code> and <code>load</code>. Here's an example:</p> <pre><code>class SerializerRegistry(object): def __init__(self): self._classes = {} def add(self, cls): self._classes[cls.__module__, cls.__name__] = cls return cls def object_hook(self, dct): module, cls_name = dct.pop('__type__', (None, None)) if cls_name is not None: return self._classes[module, cls_name].from_dict(dct) else: return dct def default(self, obj): dct = obj.to_dict() dct['__type__'] = [type(obj).__module__, type(obj).__name__] return dct registry = SerializerRegistry() @registry.add class A(object): def __init__(self, item1): self.item1 = item1 def __repr__(self): return str(self.__dict__) def to_dict(self): return dict(item1=self.item1) @classmethod def from_dict(cls, dct): return cls(**dct) s = json.dumps(A(1), default=registry.default) a = json.loads(s, object_hook=registry.object_hook) </code></pre> <p>This results in this:</p> <pre><code>&gt;&gt;&gt; s '{"item1": 1, "__type__": ["__main__", "A"]}' &gt;&gt;&gt; a {'item1': 1} </code></pre> <p>But what you really need is a function <code>default</code> that creates dictionary from the objects that you wish to serialize, and a function <code>object_hook</code> that returns an object (of the correct type) when it is given a dictionary if a dictionary isn't enough. The best approach is to have methods on the serializable classes that create a dict from the object and that construct it back, and also to have a mapping that recognizes to which class the dictionaries belong.</p> <p>You can also add an identifier to the classes to be used as an index for <code>_classes</code>. This way you wouldn't have issues if you have to move a class.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload