You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

寻求简洁高效的Python JSON转枚举(或整数)代码方案

优雅实现JSON可枚举字段值转Enum/整数的方案

核心思路

通过集中配置字段-枚举映射规则,配合递归遍历JSON结构的通用函数,实现自动匹配转换。相比手动嵌套循环,这种方式更简洁、可维护,适配任意嵌套深度的JSON结构。

具体实现步骤

1. 定义枚举映射规则

可以用Enum类(带类型校验)或直接用字典映射,把需要转换的字段路径和对应枚举关系明确声明:

from enum import Enum

# 自定义枚举类(可选,提供类型安全校验)
class BeatEnum(Enum):
    FILEBEAT = 1
    FILEBEAT2 = 2

class OutcomeEnum(Enum):
    SUCCESS = 0
    FAILURE = 1

class EventTypeEnum(Enum):
    START = 10
    STOP = 11
    SUCCESS1 = 12
    SIGNOFF = 13

# 核心映射配置:用点分隔嵌套字段路径,关联对应的枚举类/映射表
FIELD_MAPPINGS = {
    "@metadata.beat": BeatEnum,
    "event.outcome": OutcomeEnum,
    "event.type": EventTypeEnum,
    # 新增字段只需在这里添加规则
}

2. 递归遍历转换函数

写一个通用递归函数,自动遍历JSON的每个节点,匹配映射规则完成转换:

def transform_enum_fields(data, mappings, parent_path=""):
    if isinstance(data, dict):
        for key, value in data.items():
            current_path = f"{parent_path}.{key}" if parent_path else key
            # 检查当前字段是否在转换规则中
            if current_path in mappings:
                mapper = mappings[current_path]
                # 处理数组类型(比如event.type是数组)
                if isinstance(value, list):
                    data[key] = [mapper(item).value for item in value]
                else:
                    data[key] = mapper(value).value
            else:
                # 递归处理嵌套子字典
                transform_enum_fields(value, mappings, current_path)
    return data

3. 实际使用示例

把你的JSON数据传入函数即可完成批量转换:

# 修正语法后的示例JSON数据
sample_json = [
    {
        "@timestamp": "2023-05-09T11:33:09.000Z",
        "@metadata": {
            "beat": "filebeat",
            "type": "_doc",
            "version": "8.2.4",
            "_id": "0c2d32ca",
            "pipeline": "fbconst"
        },
        "event": {
            "id": "0c2d32ca",
            "category": "authentication",
            "dataset": "o365.audit",
            "module": "o365",
            "code": "AzureActiveDirectoryStsLogon",
            "kind": "event",
            "type": ["start", "success1"],
            "outcome": "success",
            "provider": "AzureActiveDirectory",
            "action": "UserLoggedIn"
        }
    },
    {
        "@timestamp": "2023-05-09T11:33:09.000Z",
        "@metadata": {
            "beat": "filebeat2",
            "type": "_doc",
            "version": "8.2.3",
            "_id": "0c2d32cb",
            "pipeline": "fbconst"
        },
        "event": {
            "id": "0c2d32cb",
            "category": "security",
            "dataset": "o365.audit",
            "module": "o365",
            "code": "AzureActiveDirectoryStsLogon",
            "kind": "event",
            "type": ["stop", "signoff"],
            "outcome": "failure",
            "provider": "AzureActiveDirectory",
            "action": "UserLoggedIn"
        }
    }
]

# 执行转换
transformed_data = [transform_enum_fields(item, FIELD_MAPPINGS) for item in sample_json]

转换后,@metadata.beat会变为1/2,event.outcome变为0/1,event.type数组元素会替换为对应的枚举值,其他字段保持原样。

方案优势

  • 可维护性:所有转换规则集中在配置里,新增/修改字段只需调整FIELD_MAPPINGS,无需改动遍历逻辑
  • 通用性:自动适配任意嵌套深度的JSON结构,不管实际数据多复杂都能处理
  • 类型安全:用Enum类可自动校验值的合法性,若传入不在枚举范围内的字符串会直接抛出异常,便于排查数据问题

如果不需要类型校验,也可以直接用字典替换Enum类(比如"@metadata.beat": {"filebeat":1, "filebeat2":2}),函数里对应改成字典取值即可。

内容的提问来源于stack exchange,提问作者Sriram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 15:05:07