有谁知道在执行 HttpResponse 时如何返回列表对象。
我努力了
HttpResponse(['a'.'b'])
但这显然行不通。
我也试过以下
return HttpResponse(Context(['a','b']),mimetype='text/plain')
但这会返回一些我不想要的额外东西
['a', 'b']{'False': False, 'None': None, 'True': True}
我只是想让它回来
['a', 'b']
谢谢
有谁知道在执行 HttpResponse 时如何返回列表对象。
我努力了
HttpResponse(['a'.'b'])
但这显然行不通。
我也试过以下
return HttpResponse(Context(['a','b']),mimetype='text/plain')
但这会返回一些我不想要的额外东西
['a', 'b']{'False': False, 'None': None, 'True': True}
我只是想让它回来
['a', 'b']
谢谢
这应该为你做
from django.utils import simplejson
json_stuff = simplejson.dumps({"list_of_jsonstuffs" : ["a", "b"]})
return HttpResponse(json_stuff, content_type ="application/json")
您可以使用 HttpResponse 子类:JsonResponse。
参考:https ://docs.djangoproject.com/en/2.0/ref/request-response/#jsonresponse-objects
对于您的实例:
from django.http import JsonResponse
return JsonResponse(['a', 'b'], safe=False)
嗨,这个可以工作:
你的意见:
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)
谢谢你的检查。
使用逗号 ( ,),而不是点 ( .) 来分隔列表元素,即:
return HttpResponse("['a', 'b']")