Skip to content

Instantly share code, notes, and snippets.

@smcoll
Created February 17, 2012 00:18
Show Gist options
  • Save smcoll/1849103 to your computer and use it in GitHub Desktop.
Save smcoll/1849103 to your computer and use it in GitHub Desktop.
more flexible JSONRenderer class
class JSONRenderer(BaseRenderer):
"""
Renderer which serializes to JSON
"""
media_type = 'application/json'
format = 'json'
ensure_ascii = True
def render(self, obj=None, media_type=None):
"""
Renders *obj* into serialized JSON.
"""
if obj is None:
return ''
# If the media type looks like 'application/json; indent=4', then
# pretty print the result.
indent = get_media_type_params(media_type).get('indent', None)
sort_keys = False
try:
indent = max(min(int(indent), 8), 0)
sort_keys = True
except (ValueError, TypeError):
indent = None
return json.dumps(obj, cls=DateTimeAwareJSONEncoder, ensure_ascii=self.ensure_ascii, indent=indent, sort_keys=sort_keys)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment