Skip to content

Commit

Permalink
support a decoding object_hook
Browse files Browse the repository at this point in the history
git-svn-id: http://simplejson.googlecode.com/svn/trunk@19 a4795897-2c25-0410-b006-0d3caba88fa1
  • Loading branch information
etrepum committed Mar 19, 2006
1 parent 40dbd8e commit 3035dac
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
12 changes: 12 additions & 0 deletions simplejson/__init__.py
Expand Up @@ -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
Expand Down
11 changes: 10 additions & 1 deletion simplejson/decoder.py
Expand Up @@ -150,6 +150,9 @@ def JSONObject(match, context, _w=WHITESPACE.match):
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)

Expand Down Expand Up @@ -221,16 +224,22 @@ class JSONDecoder(object):
_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
effect when decoding ``unicode`` objects.
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):
"""
Expand Down

0 comments on commit 3035dac

Please sign in to comment.