📖 Scenario: You are building a simple Django web app that needs to send data as JSON to the browser. This is common when making APIs or dynamic web pages that use JavaScript to fetch data.
🎯 Goal: Create a Django view that returns a JSON response using JsonResponse with a dictionary of user information.
📋 What You'll Learn
Create a dictionary called user_data with keys name, age, and city and their exact values.
Create a variable called status_code and set it to 200.
Write a Django view function called user_info that returns a JsonResponse with user_data and status=status_code.
Add the necessary import for JsonResponse from django.http.
💡 Why This Matters
🌍 Real World
APIs often send data as JSON to web browsers or other apps. Django's JsonResponse makes it easy to send JSON data from your server.
💼 Career
Knowing how to return JSON responses is essential for backend web developers building APIs or dynamic web applications.
Progress0 / 4 steps
1
Create the user data dictionary
Create a dictionary called user_data with these exact entries: 'name': 'Alice', 'age': 30, and 'city': 'New York'.
Django
Hint
Use curly braces {} to create a dictionary with the exact keys and values.
2
Set the status code variable
Create a variable called status_code and set it to the integer 200.
Django
Hint
Just assign the number 200 to the variable status_code.
3
Write the Django view function
Write a Django view function called user_info that takes a request parameter and returns a JsonResponse with user_data as data and status=status_code.
Django
Hint
Define a function with def user_info(request): and return JsonResponse(user_data, status=status_code).
4
Import JsonResponse
Add the import statement to import JsonResponse from django.http at the top of the file.
Django
Hint
Use from django.http import JsonResponse at the top of your file.
Practice
(1/5)
1. What is the main purpose of Django's JsonResponse class?
easy
A. To send JSON data as an HTTP response easily and safely
B. To render HTML templates with JSON data
C. To parse JSON data from incoming requests
D. To convert JSON strings into Python dictionaries
Solution
Step 1: Understand JsonResponse role
JsonResponse is designed to send JSON data back to the client as an HTTP response.
Step 2: Differentiate from other JSON tasks
It does not parse incoming JSON or render HTML; it only sends JSON safely with correct headers.
Final Answer:
To send JSON data as an HTTP response easily and safely -> Option A
Quick Check:
JsonResponse sends JSON response [OK]
Hint: JsonResponse sends JSON data back to clients [OK]
Common Mistakes:
Confusing JsonResponse with JSON parsing
Thinking it renders HTML templates
Assuming it converts JSON strings to dicts
2. Which of the following is the correct way to return a JSON response with a dictionary {"name": "Alice"} using JsonResponse?
easy
A. return JsonResponse([{"name": "Alice"}], safe=False)
B. return JsonResponse({"name": "Alice"})
C. return JsonResponse('[{"name": "Alice"}]')
D. return JsonResponse(json.dumps({"name": "Alice"}))
Solution
Step 1: Use JsonResponse with a dictionary
JsonResponse accepts a dictionary by default and sets safe=True, so no extra argument is needed.
Step 2: Differentiate correct usage
Passing a list of dictionaries produces a JSON array instead of a single object; passing JSON strings causes TypeError.
Final Answer:
return JsonResponse({"name": "Alice"}) -> Option B
Quick Check:
Dict input with default safe=True [OK]
Hint: Pass dict directly; no safe=False needed for dict [OK]
Common Mistakes:
Passing JSON string instead of dict
Passing a list produces JSON array instead of object
Using json.dumps inside JsonResponse
3. What will be the output of this Django view code?
from django.http import JsonResponse
def my_view(request):
data = [1, 2, 3]
return JsonResponse(data, safe=False)
medium
A. HTTP response with JSON array [1, 2, 3]
B. TypeError because safe=False is invalid
C. HTTP response with JSON string '[1, 2, 3]'
D. HTTP response with JSON object {"data": [1, 2, 3]}
Solution
Step 1: Recognize safe=False allows list data
JsonResponse by default requires dict; safe=False allows lists like [1, 2, 3].
Step 2: Understand output JSON content
The response will contain the JSON array [1, 2, 3] as the body with correct headers.
Final Answer:
HTTP response with JSON array [1, 2, 3] -> Option A
Quick Check:
safe=False lets list output [OK]
Hint: Use safe=False to return lists as JSON [OK]
Common Mistakes:
Omitting safe=False causes TypeError
Expecting JSON object instead of array
Confusing JSON string with JSON array
4. Identify the error in this Django view code:
from django.http import JsonResponse
def my_view(request):
data = ["apple", "banana"]
return JsonResponse(data)
medium
A. No error; code works fine
B. JsonResponse cannot return lists at all
C. JsonResponse requires json.dumps before returning
D. Missing safe=False causes TypeError for list data
Solution
Step 1: Check data type passed to JsonResponse
Data is a list, but JsonResponse defaults to safe=True, which only allows dicts.
Step 2: Understand error cause
Without safe=False, passing a list raises TypeError because it's unsafe to send raw lists.
Final Answer:
Missing safe=False causes TypeError for list data -> Option D
Quick Check:
List needs safe=False to avoid error [OK]
Hint: Add safe=False when returning lists [OK]
Common Mistakes:
Forgetting safe=False with lists
Trying to json.dumps before JsonResponse
Assuming JsonResponse accepts lists by default
5. You want to return a JSON response with a list of user names ["Alice", "Bob"] from a Django view. Which is the correct way to do this?
hard
A. return JsonResponse({"users": ["Alice", "Bob"]})
B. return JsonResponse(["Alice", "Bob"], safe=True)
C. return JsonResponse(["Alice", "Bob"], safe=False)
D. return JsonResponse(json.dumps(["Alice", "Bob"]))
Solution
Step 1: Decide JSON structure to return
Returning a list directly requires safe=False because JsonResponse defaults to safe=True (dict only).
Step 2: Avoid common mistakes
Passing safe=True with a list causes error; json.dumps returns string, which JsonResponse does not accept.
Final Answer:
return JsonResponse(["Alice", "Bob"], safe=False) -> Option C
Quick Check:
List with safe=False returns JSON array [OK]
Hint: Use safe=False to return JSON lists directly [OK]
Common Mistakes:
Setting safe=True with list causes error
Passing JSON string instead of Python list
Wrapping list inside dict unnecessarily
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.