简体   繁体   中英

Django minimize json in JsonResponse

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)

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)

HTTPResponse允许我们使用分隔符和json.dumps以我们指定的格式返回数据

HttpResponse(json.dumps(data, separators = (',', ':')), content_type = 'application/json')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM