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

为何该JSON对象符合条件Schema?移除数组项后报错原因解析

JSON Schema条件验证的数组行为疑问

待验证的第一个JSON对象

{
  "payment": {
    "account": [
      {
        "type": "ACCOUNT_INFORMATION",
        "identification": "2451114"
      },
      {
        "type": "XXX",
        "identification": "2451114"
      }
    ]
  }
}

对应的条件Schema

{
  "if": {
    "properties": {
      "payment": {
        "properties": {
          "account": {
            "items": {
              "properties": {
                "type": {
                  "const": "ACCOUNT_INFORMATION"
                }
              }
            }
          }
        }
      }
    }
  },
  "then": {
    "properties": {
      "payment": {
        "properties": {
          "account": {
            "items": {
              "properties": {
                "identification": {
                  "maxLength": 8,
                  "minLength": 8
                }
              }
            }
          }
        }
      }
    }
  }
}

移除第二个account项后的JSON对象

{
  "payment": {
    "account": [
      {
        "type": "ACCOUNT_INFORMATION",
        "identification": "2451114"
      }
    ]
  }
}

验证现象

  • 第一个JSON验证无错误
  • 第二个JSON因违反minLength约束报错

疑问

该现象是否因条件Schema无法应用于嵌套数组?两者是否都应报错?


解答

这跟条件Schema能不能应用于嵌套数组没关系,问题出在if条件的校验逻辑和then约束的作用范围上:

  1. if条件的判断规则
    if块的schema要求:payment.account数组的所有元素都必须满足type: "ACCOUNT_INFORMATION"。

    • 第一个JSON里存在type为XXX的account项,不满足if的schema要求,因此if判定为false,then约束不会触发,所以不会报错。
    • 第二个JSON里的唯一account项符合type要求,if判定为true,then约束生效。
  2. then约束的作用规则
    then块的schema要求:payment.account数组的所有元素的identification长度必须是8位。第二个JSON里的identification是7位("2451114"),违反了长度约束,因此报错。

结论

两者并非都应报错。只有当if条件满足时,then的约束才会生效。第一个JSON因不满足if条件,不会触发then的校验;第二个JSON满足if条件,触发校验后因长度不符合要求报错。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 22:40:56