[Python-ideas] Json object-level serializer

David Stanek dstanek at dstanek.com
Fri Jul 30 01:12:57 CEST 2010


On Thu, Jul 29, 2010 at 7:35 AM, Tarek Ziadé <ziade.tarek at gmail.com> wrote:
> Hello,
>
> 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)
> '"json"'
>
>
>
> Cheers
> Tarek
>

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.

-- 
David
blog: http://www.traceback.org
twitter: http://twitter.com/dstanek



More information about the Python-ideas mailing list