栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

成功解决:TypeError: the JSON object must be str, bytes or bytearray, not dict

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

成功解决:TypeError: the JSON object must be str, bytes or bytearray, not dict

成功解决: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}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/965362.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号