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

如何编写JSON Schema条件校验数组中mobile类型对象的endDate规则

问题原因

你之前编写的Schema不符合预期,是因为你把针对mobile类型的校验规则放在了items配置下,相当于强制要求所有type为mobile的数组元素的endDate都必须为空字符串,和需求中「至少有1个符合要求的mobile对象即可,其余mobile对象不受限制」的规则冲突。

符合要求的JSON Schema
{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "type": "object",
  "properties": {
    "contacts": {
      "type": "array",
      "minItems": 1,
      "contains": {
        "type": "object",
        "properties": {
          "type": {
            "const": "mobile"
          },
          "endDate": {
            "anyOf": [
              {
                "type": "null"
              },
              {
                "type": "string",
                "maxLength": 0
              }
            ]
          }
        },
        "required": ["type", "endDate"]
      },
      "items": {
        "type": "object",
        "properties": {
          "type": {
            "type": "string"
          },
          "endDate": {
            "type": ["string", "null"]
          },
          "number": {
            "type": "string"
          }
        },
        "required": ["type", "endDate", "number"]
      }
    }
  },
  "required": ["contacts"]
}
校验逻辑说明
  • 核心规则通过contains关键字实现:要求contacts数组中至少存在一个元素满足「type为mobile,且endDate为null或空字符串」,完全匹配你的业务要求
  • 外层items仅做基础字段类型校验,不会限制其他mobile类型对象的endDate取值,也不会对非mobile类型对象做额外规则校验
  • 已补充必要的required配置避免字段缺失导致的校验误判,你可以根据实际业务需求调整必填字段列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 20:36:00