Concept Flow - JSON response formatting
Start Flask app
Define route
Create Python dict
Use jsonify()
Return JSON response
Client receives JSON
This flow shows how a Flask app creates and sends a JSON response using jsonify.
from flask import Flask, jsonify app = Flask(__name__) @app.route('/data') def data(): return jsonify({'name': 'Alice', 'age': 30})
| Step | Action | Data State | Result |
|---|---|---|---|
| 1 | Start Flask app | No request yet | App running |
| 2 | Client requests /data | No data processed | Route data() called |
| 3 | Create dict {'name': 'Alice', 'age': 30} | dict ready | Data prepared |
| 4 | Call jsonify() with dict | dict passed to jsonify | JSON response created |
| 5 | Return JSON response | Response ready | Client receives JSON: {"name": "Alice", "age": 30} |
| 6 | End request | Response sent | Waiting for next request |
| Variable | Start | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|
| data_dict | None | {"name": "Alice", "age": 30} | {"name": "Alice", "age": 30} | No change |
| response | None | None | JSON response object | Sent to client |
Flask JSON response formatting: - Define route with @app.route - Create Python dict with data - Use jsonify(dict) to convert to JSON - Return jsonify result to send JSON response - Client receives JSON with correct headers
jsonify() in a Flask app?jsonify() function converts Python data structures into JSON format for HTTP responses.jsonify() to return JSON responses with correct headers automatically.from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/data')
def data():
info = {'name': 'Alice', 'age': 30}
return jsonify(info)jsonify(info), which sends a JSON response with the dictionary data.from flask import Flask, jsonify
import json
app = Flask(__name__)
@app.route('/info')
def info():
data = {'status': 'ok'}
return json.dumps(data)json.dumps(data), which is a JSON string but lacks HTTP headers for JSON content.jsonify() sets content-type headers correctly; returning json.dumps() alone can cause client issues.Pass the test and this pattern moves unknown