Forking simplejson

Paul Kölle paul at subsignal.org
Thu Oct 27 08:18:38 EDT 2011


Am 26.10.2011 19:34, schrieb Nathan Rice:
> Since this happily went off to the wrong recipient the first time...
>
> The python json module/simpljson are badly in need of an architecture
> update.  The fact that you can't override the encode method of
> JSONEncoder and have it work reliably without monkey patching the pure
> python encoder is a sign that something is horribly wrong.
+1

I wonder why the builtin json didn't implemented the __json__ hook. Now 
you need to write encoders for possibly arbitrary (imported/third party) 
objects.... Looks like it's not so hard to extend json.JSONEncoder to 
look for __json__ though:

 >>> import json
 >>> from functools import partial
 >>> from types import MethodType
 >>> class Encoder(json.JSONEncoder):
...     def default(self, obj):
		fn = getattr(obj, '__json__', None)
...             if fn and type(fn) == MethodType:
...                     return obj.__json__()
...             return json.JSONEncoder.default(self, obj)
...
 >>> class T(object):
...     def __json__(self):
...             return 'foo'
...
 >>> t = T()
 >>> dumps = partial(json.dumps, cls=Encoder)
 >>> dumps(dict([(1,1), (2,2), ('test',t)]))
'{"test": "foo", "1": 1, "2": 2}'
 >>>

cheers
  Paul

[snip]




More information about the Python-list mailing list