用来对象dumps
成json
字符串,然后返回将json
字符串封装成Response
对象返回给浏览器。并且他的Content-Type
是application/json
。
from django.http import JsonResponse
def index(request):
return JsonResponse({"username":"zhiliao","age":18})
默认情况下JsonResponse
只能对字典进行dumps
,如果想要对非字典的数据进行dumps
,那么需要给JsonResponse
传递一个safe=False
参数。
from django.http import JsonResponse
def index(request):
persons = ['张三','李四','王五']
return HttpResponse(persons)
以上代码会报错,应该在使用HttpResponse
的时候,传入一个safe=False
参数
return HttpResponse(persons,safe=False)