Python - json without whitespaces

PythonJsonSerialization

Python Problem Overview


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}

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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.

Solution 3 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniele BView Question on Stackoverflow
Solution 1 - Pythondonghyun208View Answer on Stackoverflow
Solution 2 - PythonHugues FontenelleView Answer on Stackoverflow
Solution 3 - PythonEkremusView Answer on Stackoverflow