From a13cdbeb255baf0a9caa4187e5693df920199ea8 Mon Sep 17 00:00:00 2001 From: David Fischer Date: Thu, 16 Jun 2016 07:08:07 -0700 Subject: [PATCH] Optionally sort JSON output --- docs/api-guide/settings.md | 10 ++++++++++ rest_framework/renderers.py | 9 ++++++--- rest_framework/settings.py | 1 + 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index f218d00ad..9514dd2d4 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -340,6 +340,16 @@ The default style is to return minified responses, in line with [Heroku's API de Default: `True` +#### SORTED_JSON + +When set to `True`, keys in JSON responses will be sorted. For example: + + {"email": "jane@example", "is_admin": false, "username": "jane"} + +When set to `False`, the JSON responses are arbitrarily ordered. + +Default: `False` + #### COERCE_DECIMAL_TO_STRING When returning decimal objects in API representations that do not support a native decimal type, it is normally best to return the value as a string. This avoids the loss of precision that occurs with binary floating point implementations. diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index 7ca680e74..d977da389 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -97,9 +97,12 @@ class JSONRenderer(BaseRenderer): separators = INDENT_SEPARATORS ret = json.dumps( - data, cls=self.encoder_class, - indent=indent, ensure_ascii=self.ensure_ascii, - separators=separators + data, + cls=self.encoder_class, + indent=indent, + ensure_ascii=self.ensure_ascii, + separators=separators, + sort_keys=api_settings.SORTED_JSON, ) # On python 2.x json.dumps() returns bytestrings if ensure_ascii=True, diff --git a/rest_framework/settings.py b/rest_framework/settings.py index 946b905c6..a80aee2cc 100644 --- a/rest_framework/settings.py +++ b/rest_framework/settings.py @@ -111,6 +111,7 @@ DEFAULTS = { # Encoding 'UNICODE_JSON': True, 'COMPACT_JSON': True, + 'SORTED_JSON': False, 'COERCE_DECIMAL_TO_STRING': True, 'UPLOADED_FILES_USE_URL': True, }