Python - 没有空格的 json

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16311562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:15:04  来源:igfitidea点击:

Python - json without whitespaces

pythonjson

提问by Daniele B

I just realized that json.dumps()adds spaces in the JSON object

我刚刚意识到json.dumps()在 JSON 对象中添加了空格

e.g.

例如

{'duration': '02:55', 'name': 'flower', 'chg': 0}

how can remove the spaces in order to make the JSON more compact and save bytes to be sent via HTTP?

如何删除空格以使 JSON 更紧凑并节省要通过 HTTP 发送的字节?

such as:

如:

{'duration':'02:55','name':'flower','chg':0}

采纳答案by donghyun208

json.dumps(separators=(',', ':'))

回答by Hugues Fontenelle

In some cases you may want to get rid of the trailing whitespacesonly. You can then use

在某些情况下,您可能只想去掉尾随的空格。然后你可以使用

json.dumps(separators=(',', ': '))

There is a space after :but not after ,.

后面有空格,:但后面没有,

This is useful for diff'ing your JSON files (in version control such as git diff), where some editors will get rid of the trailing whitespace but python json.dump will add it back.

这对于区分您的 JSON 文件(在版本控制中,例如git diff)很有用,其中一些编辑器将删除尾随空格,但 python json.dump 会将其添加回来。

Note: This does not exactly answers the question on top, but I came here looking for this answer specifically. I don't think that it deserves its own QA, so I'm adding it here.

注意:这并不能完全回答上面的问题,但我特意来这里寻找这个答案。我认为它不值得拥有自己的 QA,所以我在这里添加它。