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()
?
Simply set the configuration key JSONIFY_PRETTYPRINT_REGULAR
to False
- Flask pretty-prints JSON unless it is requested by an AJAX request (by default).