![](/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.