[Python-ideas] Json object-level serializer

Alexander Belopolsky alexander.belopolsky at gmail.com
Thu Jul 29 17:28:24 CEST 2010

On Thu, Jul 29, 2010 at 7:54 AM, M.-A. Lemburg <mal at egenix.com> wrote:
> Antoine Pitrou wrote:
>> On Thu, 29 Jul 2010 13:35:41 +0200
>> 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
>> How about letting json use the __reduce__ protocol instead?

+1.  I  think this is a very sensible idea.  Note that Tarek's request
was not for a magic method like __repr__ that would return an easy to
parse string.  Instead, the request was for a method that would return
an object that can be serialized instead of the original object and
will carry enough data to restore the original object.

> How would you then write a class that works with both pickle
> and json ?

Hopefully, for most types json would be able to use a unmodified
__reduce__ method.  If his is not enough, the reduce protocol already
has an extension mechanism.  For example, an object may implement
obj.__reduce_ex__('json') that would return json-friendly tuple
instead of pickle oriented obj.__reduce__().

> IMO, we'd need a separate method to return a JSON version of
> the object, e.g. .__json__(). I'm not sure how deserialization
> could be handled, since JSON doesn't support arbitrary object
> types.

I am afraid this was the turning point in this thread after which the
discussion went (IMO) in the wrong direction.   Again, the OP's
request was for a method that would return an object that json or
another simple serializer (say yaml) could handle, not for a method
that will return json string.

More information about the Python-ideas mailing list