Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a list object in httpresponse Django

Tags:

django

Does anyone know how to return a list object when you do HttpResponse.

I have tried

HttpResponse(['a'.'b'])

but this obviously doesn't work.

I have also tried the following

return HttpResponse(Context(['a','b']),mimetype='text/plain')

but this returns some extra thing which i dont want

['a', 'b']{'False': False, 'None': None, 'True': True}

i just want it to return

['a', 'b']

Thanks

like image 720
Kimmy Avatar asked Jul 22 '13 12:07

Kimmy


2 Answers

This should do it for you

from django.utils import simplejson
json_stuff = simplejson.dumps({"list_of_jsonstuffs" : ["a", "b"]})    
return HttpResponse(json_stuff, content_type ="application/json")
like image 120
Henrik Andersson Avatar answered Oct 04 '22 22:10

Henrik Andersson


You can use the HttpResponse subclass: JsonResponse.

Reference: https://docs.djangoproject.com/en/2.0/ref/request-response/#jsonresponse-objects

For your instance:

from django.http import JsonResponse

return JsonResponse(['a', 'b'], safe=False)
like image 22
Jingchao Luan Avatar answered Oct 04 '22 22:10

Jingchao Luan