python错误: TypeError: the JSON object must be str, bytes or bytearray, not 'dict'解决办法

版权声明:如需转载,请与我联系。WX:reborn0502 https://blog.csdn.net/gaifuxi9518/article/details/81047688

当我尝试运行以下代码,来练习使用json.loads()和json.dumps()函数时,系统给我报出了这个错误。

import json
text = {"a":1,"b":2,"c":3}
j = json.loads(text)
print(j)
Traceback (most recent call last):
  File "test.py", line 5, in <module>
    j = json.loads(text)
  File "C:\Users\Reborn\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 348, in loads
    'not {!r}'.format(s.__class__.__name__))
TypeError: the JSON object must be str, bytes or bytearray, not 'dict'

其实解决办法很简单,由于text现在是一个字典,只需要用'''符号将它转换成字符串就可以了。但我们有必要知道loads()和jumps()这两个函数的具体用法,接下来我就简单说一下。

loads()

loads(param)是将文本字符串转换为json对象的函数,其函数名是load string 的缩写,意思是加载字符串。所以其参数param必须要是一个字典型的字符串。且字典的键必须用双引号来包裹。

dumps()

dumps(param)是将json数据对象转换为文本字符串的函数,其函数名是dump string 的缩写,意思是输出字符串,所以其参数param必须要是json对象,也就是loads()函数返回的数据类型。

猜你喜欢

转载自blog.csdn.net/gaifuxi9518/article/details/81047688
今日推荐