I\'m trying to make a Django function for JSON serializing something and returning it in an HttpResponse
object.
def json_response(something):
What about a JsonResponse Class that extends HttpResponse:
from django.http import HttpResponse
from django.utils import simplejson
class JsonResponse(HttpResponse):
def __init__(self, data):
content = simplejson.dumps(data,
indent=2,
ensure_ascii=False)
super(JsonResponse, self).__init__(content=content,
mimetype='application/json; charset=utf8')
Update: Python now has its own json handler, simply use import json
instead of using simplejson
.
The Django serializers module is designed to serialize Django ORM objects. If you want to encode a regular Python dictionary you should use simplejson, which ships with Django in case you don't have it installed already.
import json
def json_response(something):
return HttpResponse(json.dumps(something))
I'd suggest sending it back with an application/javascript Content-Type header (you could also use application/json but that will prevent you from debugging in your browser):
import json
def json_response(something):
return HttpResponse(
json.dumps(something),
content_type = 'application/javascript; charset=utf8'
)
In python 2.6 and higher there is a nice JSON library, which has many functions among which is json.dumps() which serializes an object into a string.
So you can do something like this:
import json
print json.dumps({'howdy' : True })
With newer versions of Django you can just use JsonResponse provided by django.http:
from django.http import JsonResponse
def my_view(request):
json_object = {'howdy': True}
return JsonResponse(json_object)
You can find more details in the official docs.
import json
my_list = range(1,10) # a list from 1 to 10
with open('theJsonFile.json', 'w') as file_descriptor:
json.dump(my_list, file_descriptor) #dump not dumps, dumps = dump-string