gpt4 book ai didi

python - Django 最小化 JsonResponse 中的 json

转载 作者:太空宇宙 更新时间:2023-11-04 05:48:30 31 4
gpt4 key购买 nike

有没有办法最小化 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)

关于python - Django 最小化 JsonResponse 中的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31223928/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com