diff --git a/simplejson/__init__.py b/simplejson/__init__.py index 3af09031db962576b79749600338184f1ec6f150_c2ltcGxlanNvbi9fX2luaXRfXy5weQ==..ef37da1cbf1ace4aa8f860b326018f909b99d4b0_c2ltcGxlanNvbi9fX2luaXRfXy5weQ== 100644 --- a/simplejson/__init__.py +++ b/simplejson/__init__.py @@ -39,6 +39,18 @@ >>> simplejson.load(io) [u'streaming API'] +Specializing JSON object decoding:: + + >>> import simplejson + >>> def as_complex(dct): + ... if '__complex__' in dct: + ... return complex(dct['real'], dct['imag']) + ... return dct + ... + >>> simplejson.loads('{"__complex__": true, "real": 1, "imag": 2}', + ... object_hook=as_complex) + (1+2j) + Extending JSONEncoder:: >>> import simplejson diff --git a/simplejson/decoder.py b/simplejson/decoder.py index 3af09031db962576b79749600338184f1ec6f150_c2ltcGxlanNvbi9kZWNvZGVyLnB5..ef37da1cbf1ace4aa8f860b326018f909b99d4b0_c2ltcGxlanNvbi9kZWNvZGVyLnB5 100644 --- a/simplejson/decoder.py +++ b/simplejson/decoder.py @@ -150,6 +150,9 @@ end += 1 if nextchar != '"': raise ValueError(errmsg("Expecting property name", s, end - 1)) + object_hook = getattr(context, 'object_hook', None) + if object_hook is not None: + pairs = object_hook(pairs) return pairs, end pattern(r'{')(JSONObject) @@ -221,7 +224,7 @@ _scanner = Scanner(ANYTHING) __all__ = ['__init__', 'decode', 'raw_decode'] - def __init__(self, encoding=None): + def __init__(self, encoding=None, object_hook=None): """ ``encoding`` determines the encoding used to interpret any ``str`` objects decoded by this instance (utf-8 by default). It has no @@ -229,5 +232,10 @@ Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as ``unicode``. + + ``object_hook``, if specified, will be called with the result + of every JSON object decoded and its return value will be used in + place of the given ``dict``. This can be used to provide custom + deserializations (e.g. to support JSON-RPC class hinting). """ self.encoding = encoding @@ -232,5 +240,6 @@ """ self.encoding = encoding + self.object_hook = object_hook def decode(self, s, _w=WHITESPACE.match): """