[Python-ideas] Json object-level serializer

Georg Brandl g.brandl at gmx.net
Thu Jul 29 15:12:54 CEST 2010


Am 29.07.2010 14:31, schrieb M.-A. Lemburg:
> Georg Brandl wrote:
>> Am 29.07.2010 13:35, schrieb Tarek Ziadé:
>>> 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"'
>> 
>> You can do this with a very short subclass of the JSONEncoder:
>> 
>> class MyJSONEncoder(JSONEncoder):
>>     def default(self, obj):
>>         return obj.__json__()  # with a useful failure message
> 
> Does that also work with the JSON C extension ?

I think so.  The C encoder gets the default function as an argument.

Georg

-- 
Thus spake the Lord: Thou shalt indent with four spaces. No more, no less.
Four shall be the number of spaces thou shalt indent, and the number of thy
indenting shall be four. Eight shalt thou not indent, nor either indent thou
two, excepting that thou then proceed to four. Tabs are right out.




More information about the Python-ideas mailing list