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

@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 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()

?

+3


source to share


2 answers


Just set the config key JSONIFY_PRETTYPRINT_REGULAR

to False

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



+7


source


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
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False

      



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)

+10


source







All Articles