JsonResponse对象

JsonResponse(data, encoder=DjangoJSONEncoder, safe=True, json_dumps_params=None, **kwargs)
  • 示例
>>> from django.http import JsonResponse
>>> response = JsonResponse({'foo': 'bar'})
>>> response.content
b'{"foo": "bar"}'
>>> response = JsonResponse([1, 2, 3], safe=False)
  • JsonResponse返回json格式的数据,只接收两种数据 list(列表),dict(字典)
#示例接收一个字典
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse,JsonResponse
def index(request):
	ret={"name":"python"}
	return JsonResponse(ret)
  •   示例传入列表数据
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse,JsonResponse
def index(request):
    ret={"name":"python"}
    ret_list=["json","python","linux","zabbix"]
    return JsonResponse(ret_list,safe=False)
  • 传入列表数据需要设置asfe=False,否则报下面错误
TypeError at /dashboard/
In order to allow non-dict objects to be serialized set the safe parameter to False.

  

posted @ 2021-01-11 15:22  李家琦  阅读(143)  评论(0编辑  收藏  举报