设置对象不是 JSON 可序列化的

2022-01-17 00:00:00 python json set

问题描述

当我尝试运行以下代码时:

When I try to run the following code:

import json

d = {'testing': {1, 2, 3}}
json_string = json.dumps(d)

我得到以下异常:

Traceback (most recent call last):
  File "json_test.py", line 4, in <module>
    json_string = json.dumps(d)
  File "/usr/lib/python2.7/json/__init__.py", line 243, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python2.7/json/encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python2.7/json/encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python2.7/json/encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: set([1, 2, 3]) is not JSON serializable

如何才能成功将 json.dumps 与包含 sets 的对象一起使用?

What can I do to successfully use json.dumps with objects containing sets?


解决方案

在序列化之前将集合转换为列表,或者使用自定义的 default 处理程序来这样做:

Turn sets into lists before serializing, or use a custom default handler to do so:

def set_default(obj):
    if isinstance(obj, set):
        return list(obj)
    raise TypeError

result = json.dumps(yourdata, default=set_default)

相关文章