在Python中,我们使用json.dumps将 Python 对象编码成 JSON 字符串的时候,会出现很多空格。
因为有时候我们需要处理字符串,比如加密等,但是由于多了空格,加密后肯定不一致的,那么就需要去掉这些空格。
在json.dumps官方文档里也说明了,为了美观默认会加上逗号空格和冒号空格。
按照文档里说的,我们只需要加上separators=(',',':')
这个参数就可以解决了。
官方文档:
If specified, ``separators`` should be an ``(item_separator, key_separator)``
tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and
``(',', ': ')`` otherwise. To get the most compact JSON representation,
you should specify ``(',', ':')`` to eliminate whitespace.翻译:
如果指定,`separators``应该是一个``(项目分隔符,键分隔符)``
元组。默认值为“`(',',':')``如果*indent*为``None``并且
``(“,”,“:”)“否则。要获得最紧凑的JSON表示,
您应该指定“`(',',':')``以消除空白。
实验如下:
data = { "OperatorID": "MA63HLT72", "OperatorSecret": "328e03f235304778", "SigSecret": "d1ad80b40e8d48a5", } js = json.dumps(data) print(js) js = json.dumps(data, separators=(',', ':')) print(js)
结果:
{"OperatorID": "MA63HLT72", "OperatorSecret": "328e03f235304778", "SigSecret": "d1ad80b40e8d48a5"} {"OperatorID":"MA63HLT72","OperatorSecret":"328e03f235304778","SigSecret":"d1ad80b40e8d48a5"}