Performance: Returning JSON with JsonResponse
This affects how quickly the server can send JSON data and how fast the browser can parse and render it.
from django.http import JsonResponse def my_view(request): data = {'name': 'Alice', 'age': 30} return JsonResponse(data)
from django.http import HttpResponse import json def my_view(request): data = {'name': 'Alice', 'age': 30} json_data = json.dumps(data) return HttpResponse(json_data, content_type='application/json')
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual json.dumps + HttpResponse | 0 (data only) | 0 | Minimal | [!] OK |
| Django JsonResponse | 0 (data only) | 0 | Minimal | [OK] Good |
JsonResponse class?{"name": "Alice"} using JsonResponse?from django.http import JsonResponse
def my_view(request):
data = [1, 2, 3]
return JsonResponse(data, safe=False)from django.http import JsonResponse
def my_view(request):
data = ["apple", "banana"]
return JsonResponse(data)["Alice", "Bob"] from a Django view. Which is the correct way to do this?Pass the test and this pattern moves unknown