How to return JSON Encoded response from Django View
From django 1.7 + we have built-in JsonResponse in Django. It sets Content-Type in http header to application/json, and converts the data to json also.
See the example below:
from django.http import JsonResponse
def profile(request):
data = {
'Company': 'HackersFriend',
'location': 'India',
}
return JsonResponse(data)
If your data is not a dictionary you need to pass safe = False.
return JsonResponse([1, 2, 3, 4], safe=False)
We can also fetch data from any Django model and return it as json in response from any view.
def get_articles(request):
articles = Article.objects.all().values('title', 'content') # or put just .values() to get all fields
articles_list = list(articles) # we must convert the QuerySet to a list object
return JsonResponse(articles_list, safe=False)
We can also do return Json response manually using HttpResponse object.
import json
from django.http import HttpResponse
def profile(request):
data = {
'company': 'HackersFriend',
'location': 'India',
}
dump = json.dumps(data)
return HttpResponse(dump, content_type='application/json')