0
0
Flaskframework~5 mins

JSON responses with jsonify in Flask

Choose your learning style9 modes available
Introduction

We use jsonify to send data from a Flask app to a browser in a format that is easy to read and use. It turns Python data into JSON, which is like a universal language for data.

When you want to send data from your Flask server to a web page or app.
When you build APIs that other programs or websites will use.
When you want to send structured data like lists or dictionaries as a response.
When you want to make sure the data is sent with the correct content type for JSON.
When you want to avoid manually converting data to JSON and setting headers.
Syntax
Flask
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/some_route')
def some_function():
    data = {'key': 'value', 'numbers': [1, 2, 3]}
    return jsonify(data)

jsonify automatically converts Python dictionaries and lists into JSON format.

It also sets the HTTP response content type to application/json.

Examples
Sends a simple JSON object with a greeting message.
Flask
return jsonify({'message': 'Hello, world!'})
You can pass keyword arguments directly to jsonify instead of a dictionary.
Flask
return jsonify(name='Alice', age=30)
Sends a JSON array (list) as the response.
Flask
return jsonify([1, 2, 3, 4])
Sample Program

This Flask app has one route /user that sends user information as JSON. When you visit http://localhost:5000/user, you get a JSON response with the user's name, age, and hobbies.

Flask
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/user')
def user_info():
    user = {
        'name': 'John Doe',
        'age': 28,
        'hobbies': ['reading', 'hiking', 'coding']
    }
    return jsonify(user)

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Always use jsonify instead of json.dumps to ensure proper headers and encoding.

jsonify can handle nested dictionaries and lists easily.

Remember to import jsonify from flask before using it.

Summary

jsonify converts Python data to JSON and sets the right response headers.

Use it to send data from Flask to browsers or other apps in a simple, standard way.

It works with dictionaries, lists, and keyword arguments for easy JSON responses.