【问题标题】:Django minimize json in JsonResponseDjango在JsonResponse中最小化json
【发布时间】:2015-07-04 18:28:49
【问题描述】:

有没有办法最小化 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 总是会像这样间隔键值对。
  • 传递原始值json.dumps(separators=(',', ':'))
  • 真可惜。通过 HttpResponse 和 json.dumps 手动创建 json 响应怎么样?使用字典的键和值之间会有空格吗?

标签: python json django jsonresponse


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    HttpResponse(json.dumps(data, separators = (',', ':')), content_type = 'application/json')
    

    【讨论】:

      猜你喜欢
      • 2014-12-10
      • 2017-01-29
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      • 2021-06-12
      • 2016-04-20
      • 2019-11-21
      • 1970-01-01
      相关资源
      最近更新 更多