Performance: JSON response formatting
This affects how quickly the server sends data and how fast the browser can parse and render the response.
from flask import Flask, jsonify app = Flask(__name__) @app.route('/data') def data(): data = {'name': 'Alice', 'age': 30, 'city': 'Wonderland'} return jsonify(data) # compact JSON response
from flask import Flask, Response import json app = Flask(__name__) @app.route('/data') def data(): data = {'name': 'Alice', 'age': 30, 'city': 'Wonderland'} json_str = json.dumps(data, indent=4) # pretty print with spaces return Response(json_str, mimetype='application/json')
| Pattern | Payload Size | Network Transfer | Parsing Time | Verdict |
|---|---|---|---|---|
| Pretty Printed JSON | Large (extra spaces/newlines) | Longer transfer | Longer parse time | [X] Bad |
| Compact JSON with jsonify | Smaller (no extra whitespace) | Faster transfer | Faster parse time | [OK] Good |
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