成功解决:TypeError: the JSON object must be str, bytes or bytearray, not dict
前言
本文已收录于:《告别Bug》专栏
本专栏用于记录学习和工作中遇到的各种疑难Bug问题及解决思路+解决方法,包括程序安装、运行程序过程中的问题等等,订阅专栏后如遇到其他问题可私聊帮忙解决!!!
文章目录- 报错问题
- 报错原因
- 解决方法
我的代码:
import json
data = {"name": '小白', "age": 20}
print(data, type(data))
dic_str = json.loads(data)
print(dic_str)
报错内容:
Traceback (most recent call last): File "E:/Python学习/2.py", line 5, in报错原因dic_str = json.loads(data) File "F:Python3.8libjson__init__.py", line 341, in loads raise TypeError(f'the JSON object must be str, bytes or bytearray, ' {'name': '小白', 'age': 20} TypeError: the JSON object must be str, bytes or bytearray, not dict
报错内容翻译:TypeError:JSON对象必须是str、bytes或bytearray,而不是dict
报错原因:单引号的字符串不符合Json的标准格式
解决方法解决方法:现在是一个字典,用str将它转换成字符串,使用replace把单引号换成双引号
代码修改:
import json
data = {"name": '小白', "age": 20}
print(data, type(data))
dic_str = json.loads(str(data).replace("'", """))
print(dic_str)
再次运行:
{'name': '小白', 'age': 20}
{'name': '小白', 'age': 20}



