On Thu, Jul 29, 2010 at 7:35 AM, Tarek Ziadé email@example.com wrote:
What about adding in the json package the ability for an object to provide a different object to serialize ? This would be useful to translate a class into a structure that can be passed to json.dumps
So, it __json__ is provided, its used for serialization instead of the object itself:
import json class MyComplexClass(object):
... def __json__(self): ... return 'json' ...
o = MyComplexClass() json.dumps(o)
In my experience serializing an object is usually not a concern of the object itself. I do not want to have to touch every object in my system when I need an alternate format.
The pattern I currently use is to hint, as a class-level tuple, the fields that should be serialized. django-piston has a good working example of this pattern. It becomes a bit unruly when you have a big object graph, but I typically keep my object models shallow.