Skip to content
Snippets Groups Projects
Commit ef37da1cbf1a authored by Bob Ippolito's avatar Bob Ippolito
Browse files

support a decoding object_hook

git-svn-id: http://simplejson.googlecode.com/svn/trunk@19 a4795897-2c25-0410-b006-0d3caba88fa1
parent 3af09031db96
No related branches found
No related tags found
No related merge requests found
...@@ -39,6 +39,18 @@ ...@@ -39,6 +39,18 @@
>>> simplejson.load(io) >>> simplejson.load(io)
[u'streaming API'] [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:: Extending JSONEncoder::
>>> import simplejson >>> import simplejson
......
...@@ -150,6 +150,9 @@ ...@@ -150,6 +150,9 @@
end += 1 end += 1
if nextchar != '"': if nextchar != '"':
raise ValueError(errmsg("Expecting property name", s, end - 1)) 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 return pairs, end
pattern(r'{')(JSONObject) pattern(r'{')(JSONObject)
...@@ -221,7 +224,7 @@ ...@@ -221,7 +224,7 @@
_scanner = Scanner(ANYTHING) _scanner = Scanner(ANYTHING)
__all__ = ['__init__', 'decode', 'raw_decode'] __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`` ``encoding`` determines the encoding used to interpret any ``str``
objects decoded by this instance (utf-8 by default). It has no objects decoded by this instance (utf-8 by default). It has no
...@@ -229,5 +232,10 @@ ...@@ -229,5 +232,10 @@
Note that currently only encodings that are a superset of ASCII work, Note that currently only encodings that are a superset of ASCII work,
strings of other encodings should be passed in as ``unicode``. 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.encoding = encoding
...@@ -232,5 +240,6 @@ ...@@ -232,5 +240,6 @@
""" """
self.encoding = encoding self.encoding = encoding
self.object_hook = object_hook
def decode(self, s, _w=WHITESPACE.match): def decode(self, s, _w=WHITESPACE.match):
""" """
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment