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

如何为JSON Schema添加父/母ID与邮箱的互斥必填规则?

JSON Schema 实现父母信息二选一规则

现有基础Schema结构

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "properties": {
    "person_id": {
      "type": "string"
    },
    "email": {
      "type": "string"
    },
    "father_id": {
      "type": "string",
      "format": "uuid"
    },
    "father_email": {
      "type": "string",
      "format": "email"
    },
    "mother_id": {
      "type": "string",
      "format": "uuid"
    },
    "mother_email": {
      "type": "string"
    }
  },
  "required": [
    "person_id",
    "email"  
    ],
  "additionalProperties": false
}

需求说明

  • 必须填写father_id或father_email其中一项,不可同时填写
  • 必须填写mother_id或mother_email其中一项,不可同时填写

已实现的父亲信息规则

你已经写出了针对父亲信息的oneOf规则,确保二选一且不同时填写:

"oneOf": [
  {
    "required": [
      "father_email"
    ]
  },
  {
    "required": [
      "father_id"
    ]
  }
]

完整实现方案

要同时满足父母双方的规则,只需把两个oneOf规则用allOf包裹,让两组规则同时生效。完整Schema如下:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "properties": {
    "person_id": {
      "type": "string"
    },
    "email": {
      "type": "string"
    },
    "father_id": {
      "type": "string",
      "format": "uuid"
    },
    "father_email": {
      "type": "string",
      "format": "email"
    },
    "mother_id": {
      "type": "string",
      "format": "uuid"
    },
    "mother_email": {
      "type": "string"
    }
  },
  "required": [
    "person_id",
    "email"  
  ],
  "additionalProperties": false,
  "allOf": [
    {
      "oneOf": [
        { "required": ["father_email"] },
        { "required": ["father_id"] }
      ]
    },
    {
      "oneOf": [
        { "required": ["mother_email"] },
        { "required": ["mother_id"] }
      ]
    }
  ]
}

规则解释

  • allOf:保证内部的每一组规则都必须被满足,即父母双方的二选一要求同时生效
  • 每组oneOf:对应一方的信息约束,只能选择其中一个字段填写,避免同时提交两个字段的情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 08:32:09