python - 将 Python 枚举编码为 JSON

标签 python json enums python-3.6

我有一个字典,其中一些键是 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/

相关文章:

javascript - 数据通过 websocketpp 返回为 json,但通过 messagepack 返回为 Blob

javascript - 由于点 ID 导致 JSON 调用出错

java - Jquery函数将java数据转换为json

swift - Swift 中的枚举和案例

java - 如何在对话框中使用枚举来使用 JComboBox

Python 模块依赖

python - 使用 sqlalchemy.engine.url.URL 为 mssql+pyodbc 构建连接 URL

python - 在Amazon EMR上运行mrjob,不支持t2.micro

enums - 从函数返回内联定义的枚举?

python - 将 Neo4j 事务与 Python Bolt 驱动程序结合使用