TypeError the JSON object must be str, bytes or bytearray, not ‘list‘

简介: TypeError the JSON object must be str, bytes or bytearray, not ‘list‘

在使用python的jason库时,偶然碰到以下问题

TypeError: the JSON object must be str, bytes or bytearray, not ‘list’

通过如下代码可复现问题

>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> import json
>>> ra = json.loads(a) 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\Python36\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 'list'

分析可知,python中的列表如果要通过json库解析为jason对象,就会出现以上提示。意思是,jason的对象必须是字符串,字节或字节数组,不能是列表。如果将 a 通过 str(a),在调用 loads,则不会出现以上问题。

>>> a   
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> str(a)                 
'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'
>>> json.loads(str(a)) 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

》扩展说明 》

jason导入数据

jason.load

jason.loads 其中s表示字符串

jason 导出数据

f = open(‘./data/test.txt’, ‘r’)

jason.dump(data, f)

jason.dumps

相关文章
|
3天前
|
JSON 前端开发 JavaScript
json字符串如何转为list对象?
json字符串如何转为list对象?
14 7
|
2月前
|
JSON 算法 算法框架/工具
【python】python指南(十二):Json与dict、list互相转换
【python】python指南(十二):Json与dict、list互相转换
17 0
|
2月前
|
TensorFlow API 算法框架/工具
【Tensorflow+keras】解决使用model.load_weights时报错 ‘str‘ object has no attribute ‘decode‘
python 3.6,Tensorflow 2.0,在使用Tensorflow 的keras API,加载权重模型时,报错’str’ object has no attribute ‘decode’
35 0
|
3月前
|
存储 JSON JavaScript
【Python】已完美解决:TypeError: the JSON object must be str, bytes or bytearray, not dict
【Python】已完美解决:TypeError: the JSON object must be str, bytes or bytearray, not dict
85 1
|
3月前
|
Python
stack=s+stack#TypeError: can only concatenate str (not “list“) to str
stack=s+stack#TypeError: can only concatenate str (not “list“) to str
|
3月前
|
JSON 前端开发 数据格式
【Python】已解决:TypeError: Object of type JpegImageFile is not JSON serializable
【Python】已解决:TypeError: Object of type JpegImageFile is not JSON serializable
58 0
|
3月前
|
开发者 Python
【Python】已解决:TypeError: descriptor ‘index‘ for ‘list‘ objects doesn‘t apply to a ‘str‘ object
【Python】已解决:TypeError: descriptor ‘index‘ for ‘list‘ objects doesn‘t apply to a ‘str‘ object
73 0
|
3月前
|
开发者 Python
【Python】已解决:TypeError: a bytes-like object is required, not ‘int’
【Python】已解决:TypeError: a bytes-like object is required, not ‘int’
77 0
|
3月前
|
存储 语音技术 Python
语音识别,函数综合案例,黑马ATM,/t/t一个对不齐,用两个/t,数据容器入门,数据容器可以分为列表(list)、元组(tuple)、字符串(str)、集合(set)、字典(dict)
语音识别,函数综合案例,黑马ATM,/t/t一个对不齐,用两个/t,数据容器入门,数据容器可以分为列表(list)、元组(tuple)、字符串(str)、集合(set)、字典(dict)
|
11天前
|
XML 存储 JSON
Twaver-HTML5基础学习(19)数据容器(2)_数据序列化_XML、Json
本文介绍了Twaver HTML5中的数据序列化,包括XML和JSON格式的序列化与反序列化方法。文章通过示例代码展示了如何将DataBox中的数据序列化为XML和JSON字符串,以及如何从这些字符串中反序列化数据,重建DataBox中的对象。此外,还提到了用户自定义属性的序列化注册方法。
27 1
下一篇
无影云桌面