Python - 没有空格的json

original title: "Python - json without whitespaces"


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


{'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:




  • 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.