Performance: JSON responses with jsonify
This affects the speed of sending JSON data from the server to the browser and how quickly the browser can start rendering or processing the response.
from flask import Flask, jsonify app = Flask(__name__) @app.route('/data') def data(): data_dict = {'name': 'Alice', 'age': 30} return jsonify(data_dict)
from flask import Flask, Response import json app = Flask(__name__) @app.route('/data') def data(): data_dict = {'name': 'Alice', 'age': 30} json_str = json.dumps(data_dict) return Response(json_str, mimetype='application/json')
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual json.dumps + Response | 0 (server-side only) | 0 | 0 | [!] OK but slower server response |
| Flask jsonify | 0 (server-side only) | 0 | 0 | [OK] Fast, optimized server response |
jsonify function in Flask do?jsonify function is designed to convert Python data structures like dictionaries or lists into JSON format.jsonify in Flask?jsonify({'key': value}).jsonify. return json.dumps({'name': 'Alice', 'age': 30}) uses json.dumps which returns a string, not a Flask response. return jsonify('name': 'Alice', 'age': 30) has incorrect syntax missing braces. return jsonify('name', 'Alice', 'age', 30) passes multiple positional arguments, causing a TypeError.from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/data')
def data():
return jsonify({'success': True, 'count': 5})jsonify function returns a Flask response with the content type set to application/json.jsonify({'success': True, 'count': 5}), the content type will be application/json.jsonify:from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/info')
def info():
data = {'name': 'Bob', 'age': 25}
return jsonify(data['name'], data['age'])jsonify(data['name'], data['age']) passing two separate arguments instead of one dictionary or list.jsonify expects a single argument like a dictionary, list, or keyword arguments, not multiple positional arguments.jsonify. Which code correctly combines a list and a message in the JSON response?Pass the test and this pattern moves unknown