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

目录
打赏
0
0
1
0
3
分享
相关文章
json字符串如何转为list对象?
json字符串如何转为list对象?
674 7
【python】python指南(十二):Json与dict、list互相转换
【python】python指南(十二):Json与dict、list互相转换
38 0
【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
415 1
【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’
105 0
使用jackson和fastjson实现list与json互转
使用jackson和fastjson实现list与json互转
|
8月前
|
stack=s+stack#TypeError: can only concatenate str (not “list“) to str
stack=s+stack#TypeError: can only concatenate str (not “list“) to str
【Python】已解决:TypeError: Object of type JpegImageFile is not JSON serializable
【Python】已解决:TypeError: Object of type JpegImageFile is not JSON serializable
144 0
|
8月前
|
【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
204 0
语音识别,函数综合案例,黑马ATM,/t/t一个对不齐,用两个/t,数据容器入门,数据容器可以分为列表(list)、元组(tuple)、字符串(str)、集合(set)、字典(dict)
语音识别,函数综合案例,黑马ATM,/t/t一个对不齐,用两个/t,数据容器入门,数据容器可以分为列表(list)、元组(tuple)、字符串(str)、集合(set)、字典(dict)
Java基础-常用API-Object类
继承是面向对象编程的重要特性,允许从已有类派生新类。Java采用单继承机制,默认所有类继承自Object类。Object类提供了多个常用方法,如`clone()`用于复制对象,`equals()`判断对象是否相等,`hashCode()`计算哈希码,`toString()`返回对象的字符串表示,`wait()`、`notify()`和`notifyAll()`用于线程同步,`finalize()`在对象被垃圾回收时调用。掌握这些方法有助于更好地理解和使用Java中的对象行为。
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等