esnme/ultrajson — pull request #37 by aelse (2012-03-09 12:49:30+00:00)
Title: Added 'default' decoder to ujson.dumps

Hi,

This series of patches adds the ```default``` option to ujson.dumps.

You're probably already aware that in other libraries the default option allows you to provide a function to have objects decoded by prior to serialization. eg.

```
>>> import json
>>> class Message(object):
... msg = ''
... def __init__(self, msg):
... self.msg = msg
...
>>> m = Message('test')
>>> json.dumps(m)
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python2.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/usr/lib/python2.7/json/encoder.py", line 201, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib/python2.7/json/encoder.py", line 264, in iterencode
return _iterencode(o, 0)
File "/usr/lib/python2.7/json/encoder.py", line 178, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <__main__.Message object at 0xf5b3d0> is not JSON serializable
>>> json.dumps(m, default=lambda x: x.__dict__)
'{"msg": "test"}'
```

ujson already handles this particular object natively. Programmers who wish to decode their own objects (for whatever reason) do not get the convenience of ```default``` with ujson currently. This is more problematic for other libraries which support multiple json implementations and rely on this feature being available. Hence this request originated from work on the ZeroMQ python bindings. https://github.com/zeromq/pyzmq/pull/188

I have included the patch, benchmark and unit tests in separate commits for convenience.