Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python json.dumps(<val>) to output minified json?

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.)

like image 434
Jimmy Huch Avatar asked Oct 20 '15 09:10

Jimmy Huch


People also ask

What's the difference between JSON dump and JSON dumps?

json. dump() method used to write Python serialized object as JSON formatted data into a file. json. dumps() method is used to encodes any Python object into JSON formatted String.

What is JSON dumps () method?

The dump() method is used when the Python objects have to be stored in a file. The dumps() is used when the objects are required to be in string format and is used for parsing, printing, etc, . The dump() needs the json file name in which the output has to be stored as an argument.

What does JSON dumps do in Python?

dumps() json. dumps() function converts a Python object into a json string. skipkeys:If skipkeys is true (default: False), then dict keys that are not of a basic type (str, int, float, bool, None) will be skipped instead of raising a TypeError.

How do you minify JSON in Python?

The default is (', ', ': ') if indent is None and (',', ': ') otherwise. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace.


1 Answers

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

like image 178
Eugene Soldatov Avatar answered Oct 05 '22 10:10

Eugene Soldatov