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

如何将自定义格式JSON Schema转换为Cerberus支持的标准格式

JSON自定义Schema转Cerberus兼容格式实现方案

核心映射规则

先明确两种Schema结构的字段对应关系:

  • 原始结构attributes数组下的每个属性,对应Cerberus Schema的顶级键,键名取属性的name字段值
  • 每个属性的外层固定配置"type": "list"
  • 内层schema字段根据属性的rules数组生成:
    • 匹配type为dataType的规则:若dataType为int,内层写"isint": true;其他数据类型直接写"type": "对应dataType值"
    • 若规则中存在type为notNull的配置,内层固定加"isNull": NaN
    • 可选补充description字段,根据属性语义填写对应描述

实现代码(Python示例)

import json

def convert_to_cerberus(original_schema):
    cerberus_schema = {}
    for attr in original_schema["attributes"]:
        attr_name = attr["name"]
        # 初始化属性配置
        attr_config = {
            "type": "list",
            "schema": {}
        }
        # 遍历规则填充配置
        for rule in attr["rules"]:
            if rule["type"] == "dataType":
                data_type = rule["dataType"]
                if data_type == "int":
                    attr_config["schema"]["isint"] = True
                else:
                    attr_config["schema"]["type"] = data_type
            if rule["type"] == "notNull":
                attr_config["schema"]["isNull"] = float("nan")
        # 补充描述(可根据实际业务扩展规则生成描述)
        if attr_name == "FirmName":
            attr_config["description"] = "Firm的法定名称"
        cerberus_schema[attr_name] = attr_config
    return cerberus_schema

# 测试用例
if __name__ == "__main__":
    original_input = {
        "entityName": "Firm",
        "attributes": [
            {
                "name": "FirmKey",
                "rules": [
                    {"type": "primaryKey", "severity": "reject", "operator": "", "value": "1"},
                    {"type": "dataType", "severity": "reject", "operator": "", "dataType": "int"},
                    {"type": "notNull", "severity": "reject", "operator": ""}
                ]
            },
            {
                "key": "attributedcfd6d27",
                "name": "FirmName",
                "unit": "",
                "rules": [
                    {"type": "dataType", "severity": "reject", "operator": "", "dataType": "string"}
                ]
            }
        ]
    }
    result = convert_to_cerberus(original_input)
    # 输出支持NaN的JSON
    print(json.dumps(result, indent=2, allow_nan=True, ensure_ascii=False))

扩展说明

如果后续原始Schema新增了其他规则类型,只需在遍历rules的逻辑分支中新增对应Cerberus配置的转换逻辑即可,无需修改整体转换框架。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:54:04