6

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

5
  • 1
    But what are you trying for? are you trying to return a json? a html? Commented Jul 22, 2013 at 12:44
  • i want to return a list which has many json objects in it Commented Jul 22, 2013 at 12:45
  • 1
    You won't be able to return a Python list object though. Commented Jul 22, 2013 at 12:45
  • ok thanks i will do it another way then :) Commented Jul 22, 2013 at 12:47
  • 1
    stackoverflow.com/a/798205/2108339 Commented Jul 22, 2013 at 12:48

4 Answers 4

6

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")
Sign up to request clarification or add additional context in comments.

Comments

4

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)

Comments

2

Hi this one will work:

your views :

 import json
 from django.http import HttpResponse

 def function(request):
     your_list = ['a', 'b']
     your_list_as_json = json.dumps(your_list)
     return HttpResponse(your_list_as_json)

Thank you for checking.

Comments

-1

Use comma (,), and not dot (.) to separate list elements, i.e:

return HttpResponse("['a', 'b']")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.