JsonResponse
in Django offers a concise and efficient way to return JSON
responses compared to using json.dumps
along with HttpResponse
. It simplifies the process by automatically handling serialization and setting the correct content type.
Apply with the Grit CLI
grit apply json_response_vs_json
with json
and HttpResponse
BEFORE
import json from django.http import HttpResponse def my_view(request): data = {'foo': 'bar'} json_data = json.dumps(data) return HttpResponse(json_data, content_type='application/json')
AFTER
import json from django.http import HttpResponse, JsonResponse def my_view(request): data = {'foo': 'bar'} return JsonResponse(data)
without json
and HttpResponse
PYTHON
from django.http import JsonResponse def my_view(request): data = {'foo': 'bar'} return JsonResponse(data)