Monday, 25 July 2022

python return JSON response

 https://stackoverflow.com/questions/2428092/creating-a-json-response-using-django-and-python


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'})

No comments:

Post a Comment