How to Return JSON Encoded Response for a non-dict object
In DJango, an HttpResponse sub-class helps to create a JSON-encoded response. It was called Serialized-Object response in Django < 1.7. Its default Content-Type header is set to application/JSON. The first parameter (data set), should be a dict instance. If non-dict object is passed in as the first parameter, a TypeError will be raised. To fix this error, we just need to add a parameter called “safe” to False in the method call JsonResponse.
TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False
This is the fix:
return JsonResponse(["a", "b", 1, 2], safe=False)
The safe boolean parameter defaults is True. If it’s set to False, any object can be passed for serialization (otherwise only dict instances are allowed).
Example non-dict object:
some_object = [{‘pk’: 86, “model”: “machine_models.machinemodel”, “notes”: “This is warehouse imported machine.”}]
return JsonResponse(some_object,safe=False)
A complete sample:
from django.http import JsonResponse
def home_details(req):
response = {
'id': 1,
'address': '123 Main St., San Jose, CA 95111',
'beds': 3,
'baths': 2,
'status': Sold
}
return JsonResponse(response)