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

使用Networknt JSON Schema校验器添加if-else-then关联校验规则

实现JSON Schema的if-else-then关联校验(适配Networknt校验器)

针对你需要的外层字段与内层对象关联校验需求,结合JSON Schema Draft 2019-09的if/then/else关键字,以下是修改后的Schema,实现「仅当date字段必填时,declInfo字段才为必填」的逻辑,同时支持扩展到其他内层对象:

{
  "$schema": "http://json-schema.org/draft/2019-09/schema#",
  "type": "object",
  "description": "test",
  "title": "test",
  "properties": {
    "date": {
      "type": ["string", "null", "integer"],
      "description": "Date",
      "pattern": "^[0-9]*$",
      "minLength": 1,
      "maxLength": 8
    },
    "declInfo": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "number": {
            "type": "string",
            "pattern": "^[a-zA-Z0-9._\\- ]*$",
            "minLength": 1,
            "maxLength": 19
          }
        },
        // 可选:如果date必填时,要求declInfo的子字段number也必填
        "required": ["number"]
      }
    }
  },
  "if": {
    // 触发条件:date字段存在且不为null(即有效必填场景)
    "required": ["date"],
    "properties": {
      "date": {
        "not": { "type": "null" }
      }
    }
  },
  "then": {
    // 满足条件时,强制declInfo字段必填
    "required": ["declInfo"]
  },
  "else": {
    // 不满足条件时,declInfo字段可选(也可根据需求添加禁止存在等规则)
    "properties": {
      "declInfo": {
        "nullable": true
      }
    }
  }
}

关键逻辑说明

  1. if块定义触发条件:

    • 通过required: ["date"]确保date字段存在
    • 用not: {type: "null"}排除date为null的情况,只匹配有效输入(字符串或数字类型)
  2. then块定义满足条件后的规则:

    • 添加required: ["declInfo"]强制declInfo字段必填
    • 可在内层items中添加required,进一步约束子字段(如number)的必填性
  3. else块定义不满足条件的规则:

    • 这里设置declInfo为可选,也可根据业务需求调整为禁止declInfo存在

扩展到其他内层对象

如果需要给其他字段(比如新增的otherInfo)配置类似关联规则,只需用allOf组合多组if/then/else逻辑即可:

"allOf": [
  // 原date与declInfo的关联规则
  {
    "if": {...},
    "then": {...},
    "else": {...}
  },
  // 新增的otherField与otherInfo的关联规则
  {
    "if": {
      "required": ["otherField"],
      "properties": {
        "otherField": { "not": { "type": "null" } }
      }
    },
    "then": { "required": ["otherInfo"] }
  }
]

注:Networknt的JSON Schema校验器完全支持Draft 2019-09的if/then/else语法,上述Schema可直接生效。另外修正了原Schema中的小问题:自定义正则校验需用pattern而非format,format仅用于JSON Schema预定义的格式类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 06:01:01