[Python-ideas] Json object-level serializer

Tarek Ziadé ziade.tarek at gmail.com
Thu Jul 29 15:25:20 CEST 2010

On Thu, Jul 29, 2010 at 2:51 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> On Thu, Jul 29, 2010 at 10:39 PM, Tarek Ziadé <ziade.tarek at gmail.com> wrote:
>> On Thu, Jul 29, 2010 at 2:22 PM, Georg Brandl <g.brandl at gmx.net> wrote:
>> ..
>>> 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
>>> I don't think it needs to be built into the default encoder.
>> Yes, but you need to customize in that case the encoding process and own it.
>> Having a builtin recognition of __json__ would allow you to pass your objects
>> to be serialized to any third party code that uses a plain json.dumps.
>> For instance, some web kits out there will automatically serialize
>> your objects into json strings
>> when you want to do json responses. e.g. it becomes a builtin adapter
> I'll channel PJE here and point out that this kind of magic-method
> based protocol proliferation is exactly what a general purpose
> generic-function implementation is designed to avoid (i.e. instead of
> having json.dumps check for a __json__ magic method, you'd just flag
> json.dumps as a generic function and let people register their own
> overloads).
> Each individual time this question comes up people tend to react with
> "oh, that's too complicated and overkill, but magic methods are
> simple, so let's just define another magic method". The sum total of
> all those magic methods starts to accumulate into a lot of complexity
> of its own though :P

That makes sense. OTHO, if we drop the idea of having a __magical__ method,
we could have an collections' ABC instead, called JSONSerializable,
with one method to override,

This is more about declaring the interface rather than adding yet
another __magic__ method

That's a nice OOP pattern to have imho


> Cheers,
> Nick.
> --
> Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

Tarek Ziadé | http://ziade.org

More information about the Python-ideas mailing list