如何将Python Enum成员序列化为JSON,以便将生成的JSON反序列化回Python对象?

For example, this code:

from enum import Enum    
import json

class Status(Enum):
    success = 0

json.dumps(Status.success)

导致错误的原因:

TypeError: <Status.success: 0> is not JSON serializable

我怎样才能避免呢?

推荐答案

如果您想将任意enum.Enum个成员编码为JSON,然后进行解码

PUBLIC_ENUMS = {
    'Status': Status,
    # ...
}

class EnumEncoder(json.JSONEncoder):
    def default(self, obj):
        if type(obj) in PUBLIC_ENUMS.values():
            return {"__enum__": str(obj)}
        return json.JSONEncoder.default(self, obj)

def as_enum(d):
    if "__enum__" in d:
        name, member = d["__enum__"].split(".")
        return getattr(PUBLIC_ENUMS[name], member)
    else:
        return d

The as_enum function relies on the JSON having been encoded using EnumEncoder, or something which behaves identically to it.

The restriction to members of PUBLIC_ENUMS is necessary to avoid a maliciously crafted text being used to, for example, trick calling code into saving private information (e.g. a secret key used by the application) to an unrelated database field, from where it could then be exposed (see https://chat.stackoverflow.com/transcript/message/35999686#35999686).

Example usage:

>>> data = {
...     "action": "frobnicate",
...     "status": Status.success
... }
>>> text = json.dumps(data, cls=EnumEncoder)
>>> text
'{"status": {"__enum__": "Status.success"}, "action": "frobnicate"}'
>>> json.loads(text, object_hook=as_enum)
{'status': <Status.success: 0>, 'action': 'frobnicate'}

Json相关问答推荐

使用Circe将嵌套字段添加到杨森

Jolt转换,如果任何字段为空,则将对象值设置为空

合并二维数组的Jolt表达式

如何在PowerShell中扩展JSON中的嵌套数组

JSON:将项';S键/名称移动到属性中,并使用JQ将其转换为数组

当console.log返回TRUE值时,解析的JSON中的字段未定义

使用PowerShell解析文件并获取特定行的值

使用 JQ 获取 JSON 中的替代元素(输出:JSON 对象)

jq可以在两个JSON对象列表中依次添加对象吗?

xidel:是否可以从 JSON 对象中检索特定的嵌套值?

在 postgresql 中将行转换为 json 对象

Json.Net:用于自定义命名的 JsonSerializer-Attribute

在 Postgres 中向 JSON 对象添加元素

有什么方法可以在 elasticsearch 服务器中导入 json 文件(包含 100 个文档).?

Java循环遍历Json数组?

从 VS 2017 Azure Function 开发中的 local.settings.json 读取值

如何判断 JSON 响应元素是否为数组?

将循环 struct 转换为 JSON - 有什么方法可以找到它抱怨的字段?

Python 到 JSON 序列化在十进制上失败

来自 Gson 的 JSON 字符串:删除双引号