0
0
Flaskframework~5 mins

JSON response formatting in Flask

Choose your learning style9 modes available
Introduction

JSON response formatting helps your Flask app send data in a way that other programs can easily understand and use.

When your Flask app needs to send data to a web page using JavaScript.
When building an API that other apps or services will call to get information.
When you want to send structured data like lists or dictionaries instead of plain text.
When you want to make sure the data is sent with the correct content type so browsers and clients know how to read it.
Syntax
Flask
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/data')
def data():
    response_data = {'name': 'Alice', 'age': 30}
    return jsonify(response_data)
Use jsonify() to convert Python dictionaries or lists into JSON format automatically.
Flask sets the Content-Type header to application/json when you use jsonify().
Examples
Sends a simple JSON object with a greeting message.
Flask
return jsonify({'message': 'Hello, world!'})
Sends a JSON array of numbers.
Flask
return jsonify([1, 2, 3, 4])
Sends a JSON object with multiple keys and nested data.
Flask
return jsonify(status='success', data={'id': 123, 'value': 'abc'})
Sample Program

This Flask app has one route /user that returns user information as JSON. When you visit http://localhost:5000/user, you get a JSON response with username, email, and active status.

Flask
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/user')
def user():
    user_info = {
        'username': 'johndoe',
        'email': 'johndoe@example.com',
        'active': True
    }
    return jsonify(user_info)

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

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

JSON keys and string values are always double-quoted in the response.

Boolean values in Python (True, False) become true and false in JSON.

Summary

Use jsonify() to send JSON responses easily in Flask.

JSON responses help your app communicate with browsers and other programs clearly.

Always check that your JSON data is structured correctly before sending.