问题:Python-没有空格的json

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

例如

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

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

如:

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

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

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?

such as:

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

回答 0

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

回答 1

在某些情况下,您可能只希望摆脱尾随空格。然后,您可以使用

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

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

这对区分JSON文件(在诸如的版本控制中git diff)很有用,在该版本中,某些编辑器将摆脱尾随的空白,而python json.dump将其重新添加回去。

注意:这并不能完全回答上面的问题,但是我来这里是为了寻找该答案。我认为它不应该进行自己的质量检查,因此在此添加它。

In some cases you may want to get rid of the trailing whitespaces only. 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.

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.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。