Minified JSON in flask's jsonify()

In addition to the other answer of JSONIFY_PRETTYPRINT_REGULAR, you can also get rid of the spaces between list elements by extending flask's jsonencoder, like so:

from flask import Flask
from flask.json import JSONEncoder

class MiniJSONEncoder(JSONEncoder):
    """Minify JSON output."""
    item_separator = ','
    key_separator = ':'

app = Flask(__name__)
app.json_encoder = MiniJSONEncoder
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False

The default values for item_separator and key_separator have a trailing space each, so by overriding them like this, you remove those spaces from the output.

(strictly speaking I suppose you could just set those values on the default JSONEncoder but I needed this approach since I had to overload JSONEncoder.default() for other reasons anyway)


Simply set the configuration key JSONIFY_PRETTYPRINT_REGULAR to False - Flask pretty-prints JSON unless it is requested by an AJAX request (by default).