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)
7
  • Removing spaces from where keys, values or both? Commented Jul 4, 2015 at 19:05
  • Between them, key and values can't be changed. I added an example. Commented Jul 4, 2015 at 19:12
  • I believe JsonResponse will always space key value pairs like that. Commented Jul 4, 2015 at 19:14
  • pass the raw value json.dumps(separators=(',', ':')) Commented Jul 4, 2015 at 19:17
  • What a shame. How about creating json response manually by HttpResponse and json.dumps? There will be spaces between keys and values using a dict? Commented Jul 4, 2015 at 19:19

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.