Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minified JSON in flask's jsonify()

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

like image 553
Adam Matan Avatar asked Sep 10 '14 19:09

Adam Matan


People also ask

What does Flask's Jsonify do?

jsonify is a function in Flask's flask. json module. jsonify serializes data to JavaScript Object Notation (JSON) format, wraps it in a Response object with the application/json mimetype. Note that jsonify is sometimes imported directly from the flask module instead of from flask.

Is Jsonify the same as JSON dumps?

jsonify() is a helper method provided by Flask to properly return JSON data. jsonify() returns a Response object with the application/json mimetype set, whereas json. dumps() simply returns a string of JSON data. This could lead to unintended results.

How do I return data in JSON format in Flask?

There are two methods you can use to return JSON data in your Flask application's view: by returning a Python dictionary, or by using Flask's jsonify() method.

How do I get JSON data in Flask API?

Approach 1: Using Flask jsonify object – In this approach, we are going to return a JSON response using the flask jsonify method. We are not going to use the flask-restful library in this method. Create a new python file named 'main.py'. import Flask, jsonify, and request from the flask framework.


2 Answers

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)

like image 111
robru Avatar answered Sep 19 '22 15:09

robru


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

like image 34
Sean Vieira Avatar answered Sep 19 '22 15:09

Sean Vieira