解決Django響應(yīng)JsonResponse返回json格式數(shù)據(jù)報(bào)錯(cuò)問(wèn)題
代碼
return JsonResponse({'name': 'tom'})
報(bào)錯(cuò):
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,使其接受列表
補(bǔ)充知識(shí):python 里面 JsonResponse (book_list,safe=False)
代碼為:
# 查詢(xún)所有圖書(shū) 、 增加圖書(shū)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)
遇到問(wèn)題:
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響應(yīng)JsonResponse返回json格式數(shù)據(jù)報(bào)錯(cuò)問(wèn)題就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. CentOS郵箱服務(wù)器搭建系列——SMTP服務(wù)器的構(gòu)建( Postfix )2. PHP基礎(chǔ)之生成器4——比較生成器和迭代器對(duì)象3. ASP新手必備的基礎(chǔ)知識(shí)4. Docker 啟動(dòng)Redis 并設(shè)置密碼的操作5. asp文件用什么軟件編輯6. 通過(guò)IEAD+Maven快速搭建SSM項(xiàng)目的過(guò)程(Spring + Spring MVC + Mybatis)7. JS中6個(gè)對(duì)象數(shù)組去重的方法8. vue+element開(kāi)發(fā)一個(gè)谷歌插件的全過(guò)程9. 利用CSS制作3D動(dòng)畫(huà)10. Vue axios獲取token臨時(shí)令牌封裝案例

網(wǎng)公網(wǎng)安備