在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"}