欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

解决Django响应JsonResponse返回json格式数据报错问题

程序员文章站 2022-07-09 10:36:24
代码return jsonresponse({"name": "tom"})报错:typeerror: in order to allow non-dict objects to be seriali...

代码

return jsonresponse({"name": "tom"})

报错:

typeerror: in order to allow non-dict objects to be serialized

set the safe parmeter to false

解决:

return jsonresponse({"name": "tom"}, safe=false)

增加safe=false,使其接受列表

补充知识:python 里面 jsonresponse (book_list,safe=false)

代码为:

# 查询所有图书 、 增加图书
def get(self,request):

  queryset = bookinfo.objects.all()
  book_list = []

  for book in queryset:
    book_list.append({
      'id':book.id,
      'bread':book.bread

    })
  return jsonresponse (book_list,safe=false)
 

遇到问题:

jsonresponse (book_list,safe=false)

safe=false 这是什么鬼 ?

解决方案:

down 下源码后 :

def __init__(self, data, encoder=djangojsonencoder, safe=true,
       json_dumps_params=none, **kwargs):
  if safe and not isinstance(data, dict):
    raise typeerror(
      'in order to allow non-dict objects to be serialized set the '
      'safe parameter to false.'
    )
 
 if json_dumps_params is none:
    json_dumps_params = {}
  kwargs.setdefault('content_type', 'application/json')
  data = json.dumps(data, cls=encoder, **json_dumps_params)
  super(jsonresponse, self).__init__(content=data, **kwargs)

最终答案:

'in order to allow non-dict objects to be serialized set the ' 'safe parameter to false.'

以上这篇解决django响应jsonresponse返回json格式数据报错问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。