![](/img/trans.png)
[英]Django AngularJS JSONResponse view in rendering json output
[英]Django minimize json in JsonResponse
有没有办法最小化 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 源代码中提取):
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.