0
0
Djangoframework~5 mins

Returning JSON with JsonResponse in Django - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is JsonResponse in Django?
<p><code>JsonResponse</code> is a class in Django that helps you send JSON data back to the browser easily. It formats your data as JSON and sets the right content type.</p>
Click to reveal answer
beginner
How do you import <code>JsonResponse</code> in a Django view?
<p>You import it with: <code>from django.http import JsonResponse</code></p>
Click to reveal answer
beginner
What type of data can you pass directly to JsonResponse?

You can pass a Python dictionary directly. For lists (including lists of dictionaries) or other non-dictionary types, use safe=False. Django will convert it to JSON automatically.

Click to reveal answer
intermediate
Why is JsonResponse better than using HttpResponse for JSON data?

JsonResponse automatically sets the content type to application/json and converts your data to JSON. HttpResponse requires you to do this manually.

Click to reveal answer
intermediate
How do you make JsonResponse accept non-dictionary data like a list?

Use the parameter safe=False when creating the JsonResponse. This tells Django it's okay to send data types other than dictionaries.

Click to reveal answer
What does JsonResponse automatically set in the HTTP response?
AStatus code to 404
BRedirect URL
CContent-Type to text/html
DContent-Type to application/json
Which import is needed to use JsonResponse in Django?
Afrom django.http import JsonResponse
Bfrom django.shortcuts import JsonResponse
Cimport JsonResponse from django.views
Dfrom django.urls import JsonResponse
What happens if you pass a list to JsonResponse without safe=False?
AIt raises a TypeError
BIt converts the list to a string
CIt works fine without error
DIt returns an empty JSON object
Which of these is a correct way to return JSON data in a Django view?
Areturn JsonResponse('Alice')
Breturn JsonResponse({'name': 'Alice'})
Creturn JsonResponse(['Alice'])
Dreturn JsonResponse(123)
How do you allow JsonResponse to send a list as JSON?
AWrap list in a dictionary
BConvert list to string first
CUse <code>safe=False</code> parameter
DUse <code>HttpResponse</code> instead
Explain how to return JSON data from a Django view using JsonResponse.
Think about the import, data format, and the safe parameter.
You got /4 concepts.
    What are the benefits of using JsonResponse over HttpResponse for JSON data in Django?
    Consider what JsonResponse does automatically for you.
    You got /4 concepts.