/data?from flask import Flask, jsonify app = Flask(__name__) @app.route('/data') def data(): return jsonify({'name': 'Alice', 'age': 30})
The jsonify function converts the Python dictionary into a JSON string and sets the response content-type to application/json. So the client receives JSON text, not a Python dict or HTML.
from flask import jsonify @app.route('/test') def test(): # return statement options below
Option A tries to concatenate a string to the Response object returned by jsonify, which causes a TypeError at runtime because Response objects do not support string concatenation. Options B, C, and D are valid.
from flask import Flask, jsonify app = Flask(__name__) @app.route('/info') def info(): return jsonify({'status': 'ok'})
The jsonify function sets the Content-Type header to application/json; charset=utf-8 by default to indicate JSON data encoded in UTF-8.
from flask import Flask, jsonify app = Flask(__name__) @app.route('/error') def error(): data = {'time': set([1, 2, 3])} return jsonify(data)
The set type is not supported by JSON serialization. When jsonify tries to convert the dictionary, it raises a TypeError because sets cannot be converted to JSON.
from flask import jsonify @app.route('/create') def create(): data = {'message': 'Created successfully'} # return statement options below
To set a custom status code with jsonify, return a tuple: (jsonify(data), status_code). Options B, C, and D are invalid syntax or methods.