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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22281059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:40:09  来源:igfitidea点击:

set object is not JSON serializable

pythonjsonset

提问by user3398153

When I try to run the following code:

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

import json

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

I get the following exception:

我收到以下异常:

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

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

我该怎么做才能成功使用json.dumps包含sets 的对象?

采纳答案by Martijn Pieters

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

在序列化之前将集合转换为列表,或使用自定义default处理程序来执行此操作:

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

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

回答by Kei Minagawa

You can't fix it.

你无法修复它。

This error means just "json.dumps doesn't support data type "set".You should know JSON comes from javascript. And there is no data type like Python's "set" in javascript. So Python can't treat 'set' using JSON.

此错误仅表示“json.dumps 不支持数据类型“set”。您应该知道 JSON 来自 javascript。并且在 javascript 中没有像 Python 的“set”这样的数据类型。因此 Python 不能使用JSON。

So you need another approach like @Martijn Pieters mentioned.

所以你需要另一种方法,比如提到的@Martijn Pieters。



UPDATE

更新

I forgot to say this.

我忘了说这个。

If you want to dump "set" or any other python object that is not supported JSON, you can use pickleor cPicklemodule. If you use the "dump.txt" only from Python, this may be helpful.

如果要转储“set”或任何其他不支持 JSON 的 Python 对象,可以使用picklecPickle模块。如果您仅使用 Python 中的“dump.txt”,这可能会有所帮助。

import cPickle

d = {'testing': {1, 2, 3}}

#dump
with open("pickledump.txt", "w") as fp:
    cPickle.dump(d, fp)

#load
with open("pickledump.txt", "r") as fp:
    x = cPickle.load(fp)