Python - json without whitespaces

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

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.


Compact encoding:

import json

list_1 = [1, 2, 3, {'4': 5, '6': 7}]

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

print(list_1)
[1,2,3,{"4":5,"6":7}]

Tags:

Python

Json