首先網上大多數博客沒有明確說明問題的來源
- 這個問題是由於json.dumps()函數引起的。dumps是將dict數據轉化為str數據,但是dict數據中包含byte數據所以會報錯。
- 解決:編寫一個解碼類 遇到byte就轉為str
1、新建一個.py文件
myEncoder.py
# -*- coding:utf-8 -*- # !/usr/bin/env python3 # -*- coding: utf-8 -*- import json class MyEncoder(json.JSONEncoder): def default(self, obj): """ 只要檢查到了是bytes類型的數據就把它轉為str類型 :param obj: :return: """ if isinstance(obj, bytes): return str(obj, encoding='utf-8') return json.JSONEncoder.default(self, obj)
2、在你發生錯誤的文件當中 比如a.py
- 第一步:from myEncoder import MyEncoder
- 第二步:將json.dumps(data)改寫為json.dumps(data,cls=MyEncoder,indent=4)
3、至於json.dumps函數里面的cls,indent參數請自行查詢其他博客。