Skip to main content
 首页 » 编程设计

python之Django 最小化 JsonResponse 中的 json

2025年05月04日21powertoolsteam

有没有办法最小化 JsonResponse 中的 json? 最小化我的意思是删除空格等。

多亏了这个,我可以在我的服务器上节省大约 100KB ;)。

例子:

我有一个 json:

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

我想实现这样的目标:

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

现在创建响应看起来像这样:

my_dict = dict() 
my_dict['text1'] = 1324 
my_dict['text2'] = 'abc' 
my_dict['text3'] = 'ddd' 
return JsonResponse(my_dict, safe=False) 

请您参考如下方法:

如果您在足够多的地方执行此操作,您可以创建自己的 JsonResponse,例如(大部分来自 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)