解決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. ASP常用日期格式化函數(shù) FormatDate()2. ASP新手必備的基礎(chǔ)知識(shí)3. CSS 使用Sprites技術(shù)實(shí)現(xiàn)圓角效果4. chat.asp聊天程序的編寫(xiě)方法5. 詳解瀏覽器的緩存機(jī)制6. ASP中if語(yǔ)句、select 、while循環(huán)的使用方法7. 怎樣才能用js生成xmldom對(duì)象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?8. HTML中的XML數(shù)據(jù)島記錄編輯與添加9. SXNA RSS Blog 聚合器程序10. 推薦一個(gè)好看Table表格的css樣式代碼詳解
