2

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

2 回答 2

1

如果您在足够多的地方执行此操作,您可以创建自己的 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)
于 2015-07-04T20:02:00.710 回答
0

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

HttpResponse(json.dumps(data, separators = (',', ':')), content_type = 'application/json')
于 2015-07-04T19:47:57.353 回答