gpt4 book ai didi

python - JSON 序列化 Python 枚举对象

转载 作者:行者123 更新时间:2023-12-05 01:25:40 25 4
gpt4 key购买 nike

<分区>

当使用 json.dumps(...) 将 Enum 对象序列化为 JSON 时,python 将抛出以下错误:

>>> class E(enum.Enum):
... A=0
... B=1
>>> import json
>>> json.dumps(E.A)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\guptaaman\Miniconda3\lib\json\__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "C:\Users\guptaaman\Miniconda3\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\guptaaman\Miniconda3\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\guptaaman\Miniconda3\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type E is not JSON serializable

如何使 Enum 对象 JSON 可序列化?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com