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

JSON Schema中If-then条件验证失效问题求助

JSON Schema条件验证失效问题排查与修复

问题根源分析

原Schema的两个条件验证失效,核心问题有两个:

  • 字段路径错误:email和mobile是contact对象的子属性,不是根对象的直接属性,原then规则里直接把它们写在根对象的required里,无法匹配到对应字段。
  • if条件未强制字段存在:原if块只定义了properties规则,但没有指定required,当isMerchant或cashLoan字段缺失时,JSON Schema会默认判定if条件"满足",导致then规则被错误触发;同时字段存在但值为false时,if条件也没有严格约束。

修正后的JSON Schema

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "array",
  "items": [
    {
      "type": "object",
      "properties": {
        "isMerchant": {
          "type": "boolean"
        },
        "isAgent": {
          "type": "boolean"
        },
        "cashLoan": {
          "type": "boolean"
        },
        "personalDetail": {
          "type": "string"
        },
        "contact": {
          "type": "object",
          "properties": {
            "email": {
              "type": "string"
            },
            "mobile": {
              "type": "integer"
            },
            "area": {
              "type": "string"
            },
            "state": {
              "type": "string"
            }
          },
          "required": ["state"]
        }
      },
      "required": ["isMerchant", "cashLoan", "contact"],
      "allOf": [
        {
          "if": {
            "properties": {
              "isMerchant": {"enum": [true]}
            },
            "required": ["isMerchant"]
          },
          "then": {
            "required": ["isAgent"],
            "properties": {
              "contact": {
                "required": ["email", "mobile"]
              }
            }
          }
        },
        {
          "if": {
            "properties": {
              "cashLoan": {"enum": [true]}
            },
            "required": ["cashLoan"]
          },
          "then": {
            "required": ["personalDetail"]
          }
        }
      ]
    }
  ]
}

关键修改说明

  1. 修复isMerchant条件的字段路径:
    在then规则里,通过嵌套properties.contact.required指定email和mobile为contact对象的必填字段,同时保留根对象对isAgent的必填要求。
  2. 强化if条件的严谨性:
    给两个if块都添加required字段,确保只有当isMerchant/cashLoan字段存在且值为true时,才触发对应的then验证规则,避免字段缺失时的误触发。
  3. 保留原有基础约束:
    保留原Schema中required: ["isMerchant", "cashLoan", "contact"]的基础必填规则,确保核心字段始终存在。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 16:12:46