Creating a JSON response using Django and Python
New in django 1.7
you could use JsonResponse objects.
from the docs:
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
I usually use a dictionary, not a list to return JSON content.
import json
from django.http import HttpResponse
response_data = {}
response_data['result'] = 'error'
response_data['message'] = 'Some error message'
Pre-Django 1.7 you'd return it like this:
return HttpResponse(json.dumps(response_data), content_type="application/json")
For Django 1.7+, use JsonResponse
as shown in this SO answer like so :
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
Since Django 1.7 you have a standard JsonResponse that's exactly what you need:
from django.http import JsonResponse
...
return JsonResponse(array_to_js, safe=False)
You don't even need to json.dump your array.
I use this, it works fine.
from django.utils import simplejson
from django.http import HttpResponse
def some_view(request):
to_json = {
"key1": "value1",
"key2": "value2"
}
return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')
Alternative:
from django.utils import simplejson
class JsonResponse(HttpResponse):
"""
JSON response
"""
def __init__(self, content, mimetype='application/json', status=None, content_type=None):
super(JsonResponse, self).__init__(
content=simplejson.dumps(content),
mimetype=mimetype,
status=status,
content_type=content_type,
)
In Django 1.7 JsonResponse objects have been added to the Django framework itself which makes this task even easier:
from django.http import JsonResponse
def some_view(request):
return JsonResponse({"key": "value"})