JSON response formatting helps your Flask app send data in a way that other programs can easily understand and use.
JSON response formatting in Flask
Introduction
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
Flask
return jsonify({'message': 'Hello, world!'})
Flask
return jsonify([1, 2, 3, 4])
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)
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.
Practice
1. What is the main purpose of using
jsonify() in a Flask app?easy
Solution
Step 1: Understand the role of jsonify()
Thejsonify()function converts Python data structures into JSON format for HTTP responses.Step 2: Identify the correct purpose
It is not used for HTML, database, or authentication tasks but specifically for JSON response formatting.Final Answer:
To format Python data as a JSON response easily -> Option DQuick Check:
jsonify() formats data as JSON [OK]
Hint: jsonify() turns Python data into JSON response fast [OK]
Common Mistakes:
- Thinking jsonify() creates HTML pages
- Confusing jsonify() with database functions
- Assuming jsonify() handles user login
2. Which of the following is the correct way to return a JSON response in Flask?
easy
Solution
Step 1: Review Flask JSON response syntax
Flask providesjsonify()to return JSON responses with correct headers automatically.Step 2: Compare options
return json.dumps({'key': 'value'}) returns a string without proper headers, C returns a template, D uses Response incorrectly.Final Answer:
return jsonify({'key': 'value'}) -> Option AQuick Check:
Use jsonify() to return JSON response [OK]
Hint: Use jsonify() to return JSON with correct headers [OK]
Common Mistakes:
- Using json.dumps() without setting content-type
- Returning templates instead of JSON
- Using Response without JSON serialization
3. What will be the output of this Flask route?
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/data')
def data():
info = {'name': 'Alice', 'age': 30}
return jsonify(info)medium
Solution
Step 1: Analyze the route function
The function returnsjsonify(info), which sends a JSON response with the dictionary data.Step 2: Understand jsonify output
jsonify converts the dict to JSON string and sets content-type to application/json.Final Answer:
A JSON response: {"name": "Alice", "age": 30} -> Option CQuick Check:
jsonify returns JSON response [OK]
Hint: jsonify() returns JSON string with headers, not plain dict [OK]
Common Mistakes:
- Expecting Python dict printed as string
- Thinking it returns HTML
- Assuming server error without return type
4. Identify the error in this Flask code snippet:
from flask import Flask, jsonify
import json
app = Flask(__name__)
@app.route('/info')
def info():
data = {'status': 'ok'}
return json.dumps(data)medium
Solution
Step 1: Check the return statement
The code returnsjson.dumps(data), which is a JSON string but lacks HTTP headers for JSON content.Step 2: Understand Flask JSON response best practice
Usingjsonify()sets content-type headers correctly; returning json.dumps() alone can cause client issues.Final Answer:
json.dumps() returns a string without proper response headers -> Option BQuick Check:
json.dumps() lacks JSON headers [OK]
Hint: Use jsonify(), not json.dumps(), to send JSON response [OK]
Common Mistakes:
- Returning json.dumps() string without headers
- Forgetting to import jsonify
- Misusing route decorator
5. You want to return a JSON response with a custom status code 201 and a message. Which is the correct way to do this in Flask?
hard
Solution
Step 1: Understand how to set status code with jsonify
Flask allows returning a tuple with (response, status_code) where response can be jsonify output.Step 2: Evaluate options
return jsonify({'message': 'Created'}), 201 correctly returns jsonify with status 201. return Response(json.dumps({'message': 'Created'}), status=201) misses content-type headers. return jsonify({'message': 'Created', 'status': 201}) puts status inside JSON data, not HTTP status. return {'message': 'Created'}, 201 returns dict without jsonify.Final Answer:
return jsonify({'message': 'Created'}), 201 -> Option AQuick Check:
Use jsonify() with status code tuple [OK]
Hint: Return (jsonify(data), status_code) to set HTTP status [OK]
Common Mistakes:
- Putting status code inside JSON data
- Using Response without headers
- Returning dict without jsonify
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
