56

Is there any way to have python's json.dumps(<val>) output in minified form? (i.e. get rid of extraneous spaces around commas, colons etc.)

Jimmy Huch
  • 4,400
  • 7
  • 29
  • 34

2 Answers2

108

You should set the separators parameter:

>>> json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':'))
'[1,2,3,{"4":5,"6":7}]'

From the docs:

If specified, separators should be an (item_separator, key_separator) tuple. The default is (', ', ': ') if indent is None and (',', ': ') otherwise. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace.

https://docs.python.org/3/library/json.html

https://docs.python.org/2/library/json.html

Eugene Soldatov
  • 9,755
  • 2
  • 35
  • 43
  • just a note, if anyone is still getting newlines try removing the indent argument (which I had set to zero) – MrMesees May 06 '18 at 10:00
  • test and go by what you are seeing. I can only comment on what I was seeing, but you've waited 5 months so I'm not even sure which codebase I was in without much searching – MrMesees Oct 13 '18 at 18:27
10

There's also a ujson library that works much faster and minifies the JSON by default.
Its dumps equivalent doesn't have the separators parameter and it lacks some more features like custom encoders/decoders, but I thought it might be worth to mention it here.

>>> ujson.dumps([1,2,3,{'4': 5, '6': 7}])
'[1,2,3,{"4":5,"6":7}]'
Igor Hatarist
  • 5,234
  • 2
  • 32
  • 45