Minified JSON in flask's jsonify()

11,812

Solution 1

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

Solution 2

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)

Solution 3

Flask 1.1 will add indents and spaces to the jsonify() output if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] is True (False by default) or the app is in debug mode.

From flask's source code:

indent = None
separators = (",", ":")

if current_app.config["JSONIFY_PRETTYPRINT_REGULAR"] or current_app.debug:
    indent = 2
    separators = (", ", ": ")
Share:
11,812
Adam Matan
Author by

Adam Matan

Team leader, developer, and public speaker. I build end-to-end apps using modern cloud infrastructure, especially serverless tools. My current position is R&D Manager at Corvid by Wix.com, a serverless platform for rapid web app generation. My CV and contact details are available on my Github README.

Updated on July 27, 2022

Comments

  • Adam Matan
    Adam Matan almost 2 years

    Flask offers the convenient jsonify() function, which returns a JSON object from Python variables:

    from flask import Flask, jsonify
    app = Flask(__name__)
    
    @app.route("/")
    def json_hello():
        return jsonify({x:x*x for x in range(5)}), 200
    
    if __name__ == "__main__":
        app.run(debug=True)
    

    Which returns:

    {
      "0": 0, 
      "1": 1, 
      "2": 4, 
      "3": 9, 
      "4": 16
    }
    

    (PS - note the conversion from int to string to comply with JSON).

    This indented format is wasteful for long outputs, and I prefer the minified version:

    {"1": 1, "0": 0, "3": 9, "2": 4, "4": 16}
    

    How can I get the JSON in minified version from Flask's jsonify()?

    • Lukas Graf
      Lukas Graf over 9 years
      Just use json.dumps from the standard library? (Though that's not not, strictly speaking, minified, just not pretty printed).
  • Jonatan
    Jonatan over 8 years
    While this helps, removing indentation etc, it still includes unnecessary whitespace, for example: [1, 5, 3] instead of [1,5,3].
  • L__
    L__ about 7 years
    Not sure if this is for an old version - but this is not needed as of current flask version. From flask doc (flask.pocoo.org/docs/0.12/api): This function’s response will be pretty printed if it was not requested with X-Requested-With: XMLHttpRequest to simplify debugging unless the JSONIFY_PRETTYPRINT_REGULAR config parameter is set to false. Compressed (not pretty) formatting currently means no indents and no spaces after separators.