flask.jsonify

flask.jsonify(*args, **kwargs)[source]

This function wraps dumps() to add a few enhancements that make life easier. It turns the JSON output into a Response object with the application/json mimetype. For convenience, it also converts multiple arguments into an array or multiple keyword arguments into a dict. This means that both jsonify(1,2,3) and jsonify([1,2,3]) serialize to [1,2,3].

For clarity, the JSON serialization behavior has the following differences from dumps():

  1. Single argument: Passed straight through to dumps().
  2. Multiple arguments: Converted to an array before being passed to dumps().
  3. Multiple keyword arguments: Converted to a dict before being passed to dumps().
  4. Both args and kwargs: Behavior undefined and will throw an exception.

Example usage:

from flask import jsonify

@app.route('/_get_current_user')
def get_current_user():
    return jsonify(username=g.user.username,
                   email=g.user.email,
                   id=g.user.id)

This will send a JSON response like this to the browser:

{
    "username": "admin",
    "email": "admin@localhost",
    "id": 42
}

Changed in version 0.11: Added support for serializing top-level arrays. This introduces a security risk in ancient browsers. See JSON Security for details.

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.

New in version 0.2.