Python 中 TypeError: Object of type set is not JSON serializable 错误
当我们尝试将集合对象转换为 JSON 字符串时,会出现 Python“TypeError: Object of type set is not JSON serializable”。 要解决该错误,请先将集合转换为列表,然后再将其序列化为 JSON,例如 json.dumps(list(my_set))
。
下面是错误如何发生的示例。
import json
my_set = {'a', 'b', 'c', 'd'}
# ⛔️ TypeError: Object of type set is not JSON serializable
json_str = json.dumps(my_set)
我们尝试将一个集合对象传递给 json.dumps()
方法,但该方法默认不处理集合对象
要解决该错误,请在序列化之前使用内置的 list()
类将他的集合转换为列表。
import json
my_set = {'a', 'b', 'c', 'd'}
json_str = json.dumps(list(my_set))
print(json_str) # '["b", "c", "a", "d"]'
print(type(json_str)) # <class 'str'>
默认的 JSON 编码器处理列表值,因此我们可以在序列化为 JSON 时使用原生 Python 列表而不是集合。
json.dumps
方法将 Python 对象转换为 JSON 格式的字符串。
或者,我们可以从 JSONEncoder
类扩展并在默认方法中处理转换。
import json
class SetEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, set):
return list(obj)
return json.JSONEncoder.default(self, obj)
my_set = {'a', 'b', 'c', 'd'}
json_str = json.dumps(my_set, cls=SetEncoder)
print(json_str) # 👉️ '["b", "c", "a", "d"]'
print(type(json_str)) # 👉️ <class 'str'>
我们从 JSONEncoder
类扩展而来。
JSONEncoder
类默认支持以下对象和类型。
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int 和 float 派生枚举 | number |
True | true |
False | false |
None | null |
请注意
,默认情况下,JSONEncoder
类不支持设置为 JSON 转换。
我们可以通过从类扩展并实现返回可序列化对象的 default()
方法来处理这个问题。
import json
class SetEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, set):
return list(obj)
return json.JSONEncoder.default(self, obj)
如果传入的值是集合,我们将其转换为列表并返回结果。
如果传入的对象是传入类的实例或子类,则 isinstance
函数返回 True。
在所有其他情况下,我们让基类的默认方法进行序列化。
要使用自定义 JSONEncoder
,请在调用 json.dumps()
方法时使用 cls 关键字参数指定它。
import json
class SetEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, set):
return list(obj)
return json.JSONEncoder.default(self, obj)
my_set = {'a', 'b', 'c', 'd'}
# ✅ pass cls keyword argument
json_str = json.dumps(my_set, cls=SetEncoder)
print(json_str) # 👉️ '["b", "c", "a", "d"]'
print(type(json_str)) # 👉️ <class 'str'>
如果我们不提供 cls 关键字,则使用默认的 JSONEncoder
。
总结
当我们尝试将集合对象转换为 JSON 字符串时,会出现 Python“TypeError: Object of type set is not JSON serializable”。 要解决该错误,请先将集合转换为列表,然后再将其序列化为 JSON,例如 json.dumps(list(my_set))
。