当我尝试运行以下代码时:
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的对象?
json.dumps
set
在序列化之前将集合变成列表,或使用自定义default处理程序来这样做:
default
def set_default(obj): if isinstance(obj, set): return list(obj) raise TypeError result = json.dumps(yourdata, default=set_default)