esnme/ultrajson — pull request #33 by kmanley (2012-01-12 20:46:47+00:00)
Title: Proposed change to serializing unknown types

Previously, if an unknown datatype was encountered ujson would look for a toDict method which was required to return a Python dict. I'm proposing a change to make this more general. Now ujson will look for a json_default method instead. If this method returns a json-serializable type, it is serialized directly. Otherwise, ujson will query the returned object for a json_default method, and so on recursively.

An example use case for this is serializing instances of a bitarray class (http://pypi.python.org/pypi/bitarray). Instances of this class have a natural representation as a string of 0s and 1s.

The ujson patch allows this:

from bitarray import bitarray
class mybitarray(bitarray):
def json_default(self):
return self.to01()

and then mybitarray array instances are serialized as strings

(I also updated the former toDict test cases)