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

在依赖JSON Schema中禁止关联属性的实现方案

JSON Schema 优化需求与校验规则

现有Schema

当前使用的JSON Schema如下:

{
    "type": "object",
    "additionalProperties": false,
    "properties": {
        "abc": {
            "type": "string"
        },
        "abc@mandatory": {
            "type": "string"
        },
        "abc@optional": {
            "type": "string"
        },
        "def": {
            "type": "string"
        },
        "def@mandatory": {
            "type": "string"
        },
        "def@optional": {
            "type": "string"
        }
    },
    "dependentSchemas": {
        "abc": {
            "required": [
                "abc@mandatory"
            ]
        },
        "def": {
            "required": [
                "def@mandatory"
            ]
        }
    }
}

该Schema已实现:当abc/def这类主属性存在时,必须同时包含对应的xxx@mandatory属性。

新增需求

需要补充以下规则,且要支持任意多组类似def与def@...的组合,避免新增元素导致Schema过度膨胀:

  • 当主属性(如abc)不存在时,其对应的所有附属属性(如abc@mandatory、abc@optional)都不能存在;
  • 禁止属性时要采用优雅的方式,避免用矛盾规则造成错误信息混淆。

背景说明

这些JSON数据最终要转换为XML格式,示例如下:

<abc mandatory="foo" optional="bar">Some value</abc>

对应关系:

  • 不带@的字段(如abc)对应XML元素的文本内容;
  • 带@的字段(如abc@mandatory)对应XML元素的属性;
  • @mandatory后缀的属性是对应XML元素的必填属性,但XML元素本身是可选的——如果元素不存在,其对应的所有属性也不能存在。

校验规则明细

有效数据示例

  • 空对象:
{}
  • 仅包含abc及其必填附属属性:
{
    "abc": "exists",
    "abc@mandatory": "exists"
}
  • 仅包含def及其必填附属属性:
{
    "def": "exists",
    "def@mandatory": "exists"
}
  • 同时包含多组主属性与附属属性:
{
    "abc": "exists",
    "abc@mandatory": "exists",
    "def": "exists",
    "def@mandatory": "exists"
}

无效数据示例

  • 仅存在abc的必填附属属性:
{
    "abc@mandatory": "exists"
}
  • 仅存在abc的可选附属属性:
{
    "abc@optional": "exists"
}
  • 混合存在无效附属属性与有效组:
{
    "abc@mandatory": "exists",
    "def": "exists",
    "def@mandatory": "exists"
}

(所有仅存在附属属性、无对应主属性的情况均为无效)

实现要求

不能通过枚举所有有效组合的方式实现,必须为每组主属性及其附属属性添加独立的条件校验组。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 07:05:16