jsonify() (Flask)

jsonify() is the Flask helper that turns Python data (dicts, lists) into a JSON HTTP response. It serializes the data and sets the Content-Type header to application/json, which is the right way to return JSON from a view.

Flask

When building APIs you should return jsonify(data) rather than json.dumps(data), because jsonify produces a proper Response with the correct application/json content type and handles things like unicode and the right HTTP headers.

You can pass a dict directly, jsonify(name='Ana', age=30), or a single object, jsonify(my_dict). Modern Flask also lets you return a dict from a view and auto-converts it to JSON, but jsonify is explicit and works for lists too.

To set a status code, return a tuple: return jsonify(error='Not found'), 404. To serialize complex objects like database models, pair jsonify with a serialization library such as Marshmallow.

Syntax

from flask import jsonify
return jsonify(key=value)

Examples

Python

from flask import jsonify

@app.route("/api/user")
def user():
    return jsonify(id=1, name="Ana", active=True)

Output:

{"active":true,"id":1,"name":"Ana"}

Learn it in a lesson

See also

Back to the Dictionary