0
0
FlaskHow-ToBeginner · 3 min read

How to Use jsonify in Flask for JSON Responses

In Flask, use jsonify to convert Python dictionaries or lists into JSON responses automatically with the correct content type. Import jsonify from flask and return it from your route to send JSON data to clients.
📐

Syntax

The jsonify function takes Python data like dictionaries or lists and converts them into a Flask Response object with JSON content. It sets the Content-Type header to application/json automatically.

You can pass multiple arguments or keyword arguments to jsonify, and it will convert them into a JSON object or array.

python
jsonify(*args, **kwargs)
💻

Example

This example shows a simple Flask app with a route that returns JSON data using jsonify. When you visit /api/data, it sends a JSON response with a message and a list.

python
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/api/data')
def data():
    response_data = {
        'message': 'Hello, JSON!',
        'items': [1, 2, 3, 4]
    }
    return jsonify(response_data)

if __name__ == '__main__':
    app.run(debug=True)
Output
{"message":"Hello, JSON!","items":[1,2,3,4]}
⚠️

Common Pitfalls

  • Returning a dictionary directly: Returning a Python dictionary from a route does not set the correct content type, so clients may not recognize it as JSON.
  • Not importing jsonify: Forgetting to import jsonify causes errors.
  • Passing non-serializable data: Data like custom objects or sets that cannot be converted to JSON will cause errors.
python
from flask import Flask

app = Flask(__name__)

@app.route('/wrong')
def wrong():
    # This returns a dict but no JSON content type
    return {'message': 'This is wrong'}

@app.route('/right')
def right():
    from flask import jsonify
    return jsonify(message='This is correct')
📊

Quick Reference

Use jsonify to send JSON responses easily and correctly in Flask. Always import it from flask. Pass dictionaries, lists, or keyword arguments. Avoid returning raw dicts without jsonify.

UsageDescription
jsonify({'key': 'value'})Convert dict to JSON response with correct headers
jsonify(key='value')Pass keyword arguments to create JSON object
jsonify([1, 2, 3])Convert list to JSON array response
return jsonify(...)Use in route to send JSON data to client

Key Takeaways

Always use jsonify to return JSON responses in Flask for correct content type.
Import jsonify from flask before using it in your routes.
Pass only JSON-serializable data like dicts, lists, strings, numbers to jsonify.
Avoid returning raw Python dicts directly from routes without jsonify.
jsonify automatically sets the response content type to application/json.