Miniature JSON in jsonify () flask

The checkbox offers a handy function jsonify()

that returns a JSON object from Python variables:

from flask import Flask, jsonify
app = Flask(__name__)

def json_hello():
    return jsonify({x:x*x for x in range(5)}), 200

if __name__ == "__main__":


Which returns:

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


(PS - note the conversion from int to string for JSON conformance).

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

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


How can I get JSON minified from Flask jsonify()



source to share

2 answers


to False

- the checkbox prints JSON nicely if not requested by AJAX request (default).



In addition to the other answer, JSONIFY_PRETTYPRINT_REGULAR

you can also get rid of the spaces between list items by extending the jsonencoder checkbox, for example:

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


The defaults for item_separator

and key_separator

have trailing spaces each, so by overriding them this way, you remove those spaces from the output.

(strictly speaking, I assumed you could just set these defaults JSONEncoder

, but I needed this approach since I had to overload JSONEncoder.default()

for other reasons)



All Articles