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 file.


Step 1

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


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:


def my_function(request):
  mode = True
  output = {
   'type': 'success',
   'mode': mode

  return JsonResponse(output)