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

如何用JSON Schema实现属性的双向条件必选校验?

JSON Schema 双向约束实现需求

我已经掌握了如何根据某一属性值条件性要求另一属性存在,现在需要实现反向约束。具体场景如下:

  • 存在type属性,包含多个可选值
  • 当type取值为常量"enum"时,必须存在"enum"属性
  • 若"enum"属性存在但type取值不为"enum",则校验失败

以下是我当前使用的Schema:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://example.org/schemas/field",
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "group": {
      "type": "string"
    },
    "title": {
      "$ref": "i18n.schema.json"
    },
    "description": {
      "$ref": "i18n.schema.json"
    },
    "type": {
      "type": "string",
      "enum": [
        "boolean",
        "string",
        "strings",
        "path",
        "enum",
        "map",
        "integer",
        "password"
      ]
    },
    "default": {
      "$ref": "value.schema.json"
    },
    "required": {
      "type": "boolean"
    },
    "dependencies": {
      "type": "array",
      "items": {
        "$ref": "dependency.schema.json"
      }
    },
    "enum": {
      "type": "string"
    },
    "map": {
      "$ref": "map.schema.json"
    }
  },
  "required": [
    "name",
    "title",
    "type"
  ],
  "anyOf": [
    {
      "if": {
        "properties": {
          "type": {
            "const": "enum"
          }
        }
      },
      "then": {
        "required": [
          "enum"
        ]
      }
    },
    {
      "if": {
        "properties": {
          "type": {
            "const": "map"
          }
        }
      },
      "then": {
        "required": [
          "map"
        ]
      }
    }
  ],
  "additionalProperties": false
}

补充说明

有效JSON示例

{
    "type": "enum",
    "enum": "foo"
}

无效JSON示例

  • 存在enum属性,但type取值不为"enum":
{
    "type": "string",
    "enum": "foo"
}
  • type取值为常量"enum",但enum属性不存在:
{
    "type": "enum"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 01:10:18