Daniele B
Daniele B

Reputation: 20442

Python - json without whitespaces

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}

Upvotes: 287

Views: 129733

Answers (3)

Ekremus
Ekremus

Reputation: 287

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}]

Upvotes: 26

Hugues Fontenelle
Hugues Fontenelle

Reputation: 5435

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.

Upvotes: 78

donghyun208
donghyun208

Reputation: 4857

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

Upvotes: 467

Related Questions