Python - 没有空格的json

original title: "Python - json without whitespaces"


Translate

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}


我刚刚意识到json.dumps()在JSON对象中添加了空格,例如{'duration':'02:55','name':'flower','chg':0}如何删除空格以使JSON更紧凑,更省...

这是翻译后的摘要,如果您需要查看完整的翻译,请单击“Translate”图标


所有的回答
  • Translate
    json.dumps(separators=(',', ':'))
    

  • Translate

    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.