Skip to content

Instantly share code, notes, and snippets.

@victor-o-silva
Created April 16, 2016 23:16
Show Gist options
  • Save victor-o-silva/11d5efc05e0a557e6da73d6e54912115 to your computer and use it in GitHub Desktop.
Save victor-o-silva/11d5efc05e0a557e6da73d6e54912115 to your computer and use it in GitHub Desktop.
An easily prettifiable JsonResponse for Django
from django.http import JsonResponse as DjangoJsonResponse
class JsonResponse(DjangoJsonResponse):
"""An easily prettifiable JsonResponse.
To prettify the response's content, instantiate this class passing
``pretty=True``. The content will be prettified with a level 4 indent.
"""
def __init__(self, *args, **kwargs):
if kwargs.pop('pretty', None) is True:
json_dumps_params = kwargs.get('json_dumps_params', {})
json_dumps_params['indent'] = 4
kwargs['json_dumps_params'] = json_dumps_params
super(JsonResponse, self).__init__(*args, **kwargs)
@victor-o-silva
Copy link
Author

Requires Django>=1.7

@victor-o-silva
Copy link
Author

Test case (tested with Python 3.5.1 and Django 1.9.5)

from django.test import TestCase

class PrettifiableJsonResponseTestCase(TestCase):
    def test_list(self):
        data = [1, 2, 3]

        default_content = JsonResponse(data, safe=False).content
        self.assertEqual(default_content, b'[1, 2, 3]')

        pretty_content = JsonResponse(data, safe=False, pretty=True).content
        self.assertEqual(pretty_content, b'[\n    1,\n    2,\n    3\n]')

    def test_dict(self):
        data = {'django': 'framework', 'is': 'awesome'}

        default_content = JsonResponse(data).content
        self.assertTrue(
            default_content == b'{"django": "framework", "is": "awesome"}' or
            default_content == b'{"is": "awesome", "django": "framework"}'
        )

        pretty_content = JsonResponse(data, pretty=True).content
        self.assertTrue(
            pretty_content == b'{\n    "django": "framework",\n    "is": "awesome"\n}' or
            pretty_content == b'{\n    "is": "awesome",\n    "django": "framework"\n}'
        )

    def test_multiple_levels(self):
        data = [1, [2.1, 2.2, [2.31]], 3]

        default_content = JsonResponse(data, safe=False).content
        self.assertEqual(
            default_content,
            b'[1, [2.1, 2.2, [2.31]], 3]'
        )

        pretty_content = JsonResponse(data, safe=False, pretty=True).content
        self.assertEqual(
            pretty_content,
            b'[\n    1,\n    [\n        2.1,\n        2.2,\n        [\n            2.31\n        ]\n    ],\n    3\n]'
        )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment