我的问题可以用下面的例子来概括:
from enum import Enum
import json
class FooBarType(Enum):
standard = 0
foo = 1
bar = 2
dict = {'name': 'test', 'value': 'test', 'type': FooBarType.foo}
json.dumps(dict)
TypeError: <FooBarType.foo: 1> is not JSON serializable
我收到类型错误,因为枚举不是 JSON 可序列化的。
我主要是想实现一个 JsonEncoder
并将其添加到 json.dumps()
调用中,但我无法更改 json.dumps()
调用完成。
那么,我的问题是:
是否可以在不将编码器传递给 json.dumps()
的情况下转储 json 中的枚举,而是通过在 FooBarType
枚举中添加类方法?
我希望提取以下 json:
{'name': 'test', 'value': 'test', 'type': 'foo'}
或
{'name': 'test', 'value': 'test', 'type': 1}
最佳答案
尝试:
from enum import Enum
# class StrEnum(str, Enum):
# """Enum where members are also (and must be) strs"""
class Color(str, Enum):
RED = 'red'
GREEN = 'green'
BLUE = 'blue'
data = [
{
'name': 'car',
'color': Color.RED,
},
{
'name': 'dog',
'color': Color.BLUE,
},
]
import json
print(json.dumps(data))
结果:
[
{
"name": "car",
"color": "red"
},
{
"name": "dog",
"color": "blue"
}
]
关于python - 是否可以在不将编码器传递给 json.dumps() 的情况下将枚举转储到 json 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36699512/