Python – json without whitespaces

Question:

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}
Asked By: Daniele B

||

Answers:

json.dumps(separators=(',', ':'))
Answered By: donghyun208

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.

Answered By: Hugues Fontenelle

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}]
Answered By: Ekremus
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.