How to Return JSON-Encoded Response in Django

To return a JSON-encoded response in Django, use the JsonResponse class from django.http in your app views.py file.

 

Step 1

Open the views.py file in the app containing the function that should return JSON data. At the top of the file, import JsonResponse like this:

 

myproject/myapp/views.py
from django.http import JsonResponse

 

Step 2

In a function, build a dictionary containing your output data, then pass it as the first argument of JsonResponse like this:

 

myproject/myapp/views.py
def my_function(request):
  mode = True
  
  output = {
   'type': 'success',
   'mode': mode
  }

  return JsonResponse(output)
django