2

Is there a way to minimize a json in JsonResponse? By minimize I mean removing spaces etc.

Thanks to this I can save around 100KB on my server ;).

Example:

I have a json:

{"text1": 1324, "text2": "abc", "text3": "ddd"}

And I want to achieve something like this:

{"text1":1324,"text2":"abc","text3":"ddd"}

Now creating response looks like that:

my_dict = dict()
my_dict['text1'] = 1324
my_dict['text2'] = 'abc'
my_dict['text3'] = 'ddd'
return JsonResponse(my_dict, safe=False)
Szymon Barylak
  • 92
  • 1
  • 2
  • 8

2 Answers2

2

If you do this in enough places you could create your own JsonResponse like (mostly ripped from django source):

class JsonMinResponse(HttpResponse):
    def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError('In order to allow non-dict objects to be '
                'serialized set the safe parameter to False')
        kwargs.setdefault('content_type', 'application/json')
        data = json.dumps(data, separators = (',', ':')), cls=encoder)
        super(JsonMinResponse, self).__init__(content=data, **kwargs)
CrazyCasta
  • 26,917
  • 4
  • 45
  • 72
0

HTTPResponse allows us to return data in the format we specify using separators with json.dumps

HttpResponse(json.dumps(data, separators = (',', ':')), content_type = 'application/json')
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70