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

如何在JSON Schema中实现基于name字段的条件校验?

JSON Schema 条件校验实现方案

需求说明

当name字段值为type1时,settings对象必须包含settingsType1数组;当name值为type2时,settings对象必须包含settingsType2对象。

最终配置代码

{
  "type": "object",
  "properties": {
    "properties": {
      "type": "object",
      "properties": {
        "name": {
          "type": "string",
          "enum": ["type1", "type2"]
        },
        "settings": {
          "type": "object",
          "properties": {
            "settingsType1": {
              "type": "array"
            },
            "settingsType2": {
              "type": "object"
            }
          }
        }
      },
      "required": ["name", "settings"],
      "oneOf": [
        {
          "if": {
            "properties": {
              "name": { "const": "type1" }
            }
          },
          "then": {
            "properties": {
              "settings": { "required": ["settingsType1"] }
            }
          }
        },
        {
          "if": {
            "properties": {
              "name": { "const": "type2" }
            }
          },
          "then": {
            "properties": {
              "settings": { "required": ["settingsType2"] }
            }
          }
        }
      ]
    }
  },
  "required": ["properties"]
}

关键配置说明

  • 必填字段约束:通过required关键字确保properties、name、settings这些核心字段必须存在,避免校验逻辑失效。
  • 条件分支控制:用oneOf包裹两组if/then规则,保证只会触发与当前name值匹配的校验逻辑,符合枚举值的互斥性。
  • 精准匹配与约束:if块中用const精准匹配name的具体值,then块则通过给settings添加required约束,强制要求对应字段存在。

注:原示例中settingsType2的类型定义为string,但需求要求是object,所以代码中已调整为"type": "object",若实际需求为字符串类型,可改回原配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 19:45:46