Reputation: 837
Lets say result = {'a': 1, 'b': 2, 'c': 3}
Is there a difference between these two:
return HttpResponse(json.dumps(a))
and
return JsonResponse(a)
Upvotes: 8
Views: 14909
Reputation: 427
HTTPResponse
class HttpResponse(HttpResponseBase):
JsonReponse
class JsonResponse(HttpResponse):
Refer Django Doc
Upvotes: 0
Reputation: 3964
Try this it will pass
return HttpResponse(json.dumps("abcd"))
But if you do
return JsonResponse("abcd")
JsonResponse
will give you TypeError
if you send non serializable data (Unless safe=False
in JsonResponse)
So it is safer to send json data in JsonResponse
And in header JsonResponse
will set Content-Type: application/json
on the other hand HttpResponse
will set Content-Type: text/html; charset=utf-8
Upvotes: 3
Reputation: 8572
As doc states, main difference is
Upvotes: 8
Reputation: 1340
Django uses request and response objects to pass state through the system. Each view is responsible for returning an HttpResponse object. Using HttpResponse you need to first serialize your object to JSON.
Whereas,
Since version 1.7, Django counts with the built-in JsonResponse
class, which is a subclass of HttpResponse
. Its default Content-Type header is set to application/json, which is really convenient. It also comes with a JSON encoder, so you don’t need to serialize the data before returning the response object.
You can also refer this doc:
Upvotes: 4