# HG changeset patch # User Bob Ippolito <bob@redivi.com> # Date 1142743672 0 # Sun Mar 19 04:47:52 2006 +0000 # Node ID ef37da1cbf1ace4aa8f860b326018f909b99d4b0 # Parent 3af09031db962576b79749600338184f1ec6f150 support a decoding object_hook git-svn-id: http://simplejson.googlecode.com/svn/trunk@19 a4795897-2c25-0410-b006-0d3caba88fa1 diff --git a/simplejson/__init__.py b/simplejson/__init__.py --- 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 --- 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,8 +232,14 @@ 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 + self.object_hook = object_hook def decode(self, s, _w=WHITESPACE.match): """