add json.dumps and json.loads hook

Add properties for json.dumps and json.loads functions in JSONParser
and JSONRenderer class respectively. The classes can be easily extended
by providing custom dumps and/or loads functions.
This commit is contained in:
Jiali Chen 2014-08-11 21:03:29 +08:00
parent c6326d0a67
commit 85e92b613b
2 changed files with 4 additions and 2 deletions

View File

@ -48,6 +48,7 @@ class JSONParser(BaseParser):
media_type = 'application/json'
renderer_class = renderers.UnicodeJSONRenderer
loads_function = json.loads
def parse(self, stream, media_type=None, parser_context=None):
"""
@ -58,7 +59,7 @@ class JSONParser(BaseParser):
try:
data = stream.read().decode(encoding)
return json.loads(data)
return self.loads_function(data)
except ValueError as exc:
raise ParseError('JSON parse error - %s' % six.text_type(exc))

View File

@ -55,6 +55,7 @@ class JSONRenderer(BaseRenderer):
encoder_class = encoders.JSONEncoder
ensure_ascii = True
charset = None
dumps_function = json.dumps
# JSON is a binary encoding, that can be encoded as utf-8, utf-16 or utf-32.
# See: http://www.ietf.org/rfc/rfc4627.txt
# Also: http://lucumr.pocoo.org/2013/7/19/application-mimetypes-and-encodings/
@ -81,7 +82,7 @@ class JSONRenderer(BaseRenderer):
except (ValueError, TypeError):
indent = None
ret = json.dumps(data, cls=self.encoder_class,
ret = self.dumps_function(data, cls=self.encoder_class,
indent=indent, ensure_ascii=self.ensure_ascii)
# On python 2.x json.dumps() returns bytestrings if ensure_ascii=True,