gpt4 book ai didi

python - 将 Python 枚举编码为 JSON

转载 作者:太空狗 更新时间:2023-10-30 00:53:46 28 4
gpt4 key购买 nike

我有一个字典,其中一些键是 Enum 实例(enum.Enum 的子类)。我正在尝试根据 documentation 使用自定义 JSON 编码器类将字典编码为 JSON 字符串.我只想让输出的 JSON 中的键成为枚举名称的字符串。例如{ TestEnum.one : somevalue }将被编码为 { "one" : somevalue } .

我写了一个简单的测试用例,如下所示,我在干净的 virtualenv 中测试过它:

import json

from enum import Enum

class TestEnum(Enum):
one = "first"
two = "second"
three = "third"

class TestEncoder(json.JSONEncoder):
""" Custom encoder class """

def default(self, obj):

print("Default method called!")

if isinstance(obj, TestEnum):
print("Seen TestEnum!")
return obj.name

return json.JSONEncoder.default(self, obj)

def encode_enum(obj):
""" Custom encoder method """

if isinstance(obj, TestEnum):
return obj.name
else:
raise TypeError("Don't know how to decode this")

if __name__ == "__main__":

test = {TestEnum.one : "This",
TestEnum.two : "should",
TestEnum.three : "work!"}

# Test dumps with Encoder method
#print("Test with encoder method:")
#result = json.dumps(test, default=encode_enum)
#print(result)

# Test dumps with Encoder Class
print("Test with encoder class:")
result = json.dumps(test, cls=TestEncoder)
print(result)

我无法成功对字典进行编码(使用 Python 3.6.1)。我不断得到 TypeError: keys must be a string错误和我的自定义编码器实例的默认方法(通过 cls 方法的 json.dumps 参数提供)似乎从未被调用?我还尝试通过 default 提供自定义编码方法json.dumps 的参数方法,但这也不会被触发。

我见过涉及 IntEnum 类的解决方案,但我需要 Enum 的值是字符串。我也看到了this answer其中讨论了与从另一个类继承的枚举相关的问题。但是,我的枚举仅继承自基本 enum.Enum 类并正确响应 isinstance电话?

自定义类和方法都会生成一个 TypeError当提供给 json.dumps方法。典型的输出如下所示:

$ python3 enum_test.py

Test with encoder class
Traceback (most recent call last):
File "enum_test.py", line 59, in <module>
result = json.dumps(test, cls=TestEncoder)
File "/usr/lib64/python3.6/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/usr/lib64/python3.6/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib64/python3.6/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
TypeError: keys must be a string

我认为问题是 encode JSONEncoder 类的方法假定它知道如何序列化 Enum 类(因为触发了 iterencode 方法中的 if 语句之一),因此从不调用自定义默认方法并以序列化 Enum 失败而告终?

如有任何帮助,我们将不胜感激!

最佳答案

这是一个老问题。但是没有人给出这个非常简单的答案。

你只需要从 str 继承你的 Enum。

import json

from enum import Enum

class TestEnum(str, Enum):
one = "first"
two = "second"
three = "third"

test = {TestEnum.one : "This",
TestEnum.two : "should",
TestEnum.three : "work!"}

print(json.dumps(test))

输出:

{"first": "This", "second": "should", "third": "work!"}

关于python - 将 Python 枚举编码为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43854335/

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