257

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}
dreftymac
  • 31,404
  • 26
  • 119
  • 182
Daniele B
  • 19,801
  • 29
  • 115
  • 173
  • 4
    Python 3.4 fixes this: `Changed in version 3.4: Use (',', ': ') as default if indent is not None.` https://docs.python.org/3/library/json.html#json.dump – william_grisaitis Mar 02 '17 at 17:43

3 Answers3

422
json.dumps(separators=(',', ':'))
donghyun208
  • 4,397
  • 1
  • 15
  • 18
  • 2
    Very useful for doctests with json validation. – andilabs Dec 18 '15 at 09:29
  • 14
    And also note that `indent=0` generates newlines, while `indent=None` (default) does not in 2.7. All is clearly stated at: https://docs.python.org/3/library/json.html#json.dump – Ciro Santilli OurBigBook.com Jul 28 '16 at 14:01
  • 1
    `ujson` defaults to dumps without whitespace but sadly it doesn't support `separators` keyword so can't add space back if desired. It is a lot faster though vs built in `json`! – radtek Oct 23 '18 at 16:32
  • I arrived here trying to compare the Django `request.body` to the `request.data` so folks might find this useful `bytes(json.dumps(request.data, separators=(',', ':')), 'utf-8') == request.body` – Matt Jun 12 '20 at 14:26
73

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.

Hugues Fontenelle
  • 5,275
  • 2
  • 29
  • 44
21

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}]
Ekremus
  • 237
  • 2
  • 4