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

如何在JSON Schema中根据另一个属性值定义关联对象

JSON Schema实现属性值关联校验

可以实现你需要的属性值关联校验,核心是用oneOf结合if/then关键字(JSON Schema Draft 07及以上版本支持),或者直接在oneOf分支中定义完整的场景约束,替代原来的松散校验逻辑。

方案一:使用if/then分支约束

这种方式更清晰,保留原有properties结构的同时,通过条件判断绑定channelName和channelDetails的对应关系:

{
  "type": "object",
  "properties": {
    "channelName": {
      "type": "string",
      "enum": ["channel_type_A", "channel_type_B"]
    },
    "channelDetails": { "type": "object" }
  },
  "required": ["channelName", "channelDetails"],
  "oneOf": [
    {
      "if": {
        "properties": { "channelName": { "const": "channel_type_A" } }
      },
      "then": {
        "properties": { "channelDetails": TYPE_A }
      }
    },
    {
      "if": {
        "properties": { "channelName": { "const": "channel_type_B" } }
      },
      "then": {
        "properties": { "channelDetails": TYPE_B }
      }
    }
  ]
}
  • required确保两个属性必须存在
  • oneOf保证只能匹配其中一个分支的约束
  • 每个分支通过if判断channelName的取值,then强制channelDetails必须符合对应的TYPE_A/TYPE_B结构

方案二:直接定义完整场景结构

如果不需要保留外层的properties结构,也可以直接在oneOf中定义每个合法场景的完整对象约束:

{
  "type": "object",
  "oneOf": [
    {
      "properties": {
        "channelName": { "const": "channel_type_A" },
        "channelDetails": TYPE_A
      },
      "required": ["channelName", "channelDetails"],
      "additionalProperties": false
    },
    {
      "properties": {
        "channelName": { "const": "channel_type_B" },
        "channelDetails": TYPE_B
      },
      "required": ["channelName", "channelDetails"],
      "additionalProperties": false
    }
  ]
}
  • 每个分支直接限定channelName的固定值和对应的channelDetails结构
  • additionalProperties: false可以限制对象不能包含其他未定义的属性(根据需求可选)

关于dependencies的说明

你提到的dependencies关键字确实主要用于校验属性是否存在的依赖关系,无法直接实现基于属性值的关联约束,因此上述两种方案是更合适的选择。

内容的提问来源于stack exchange,提问作者Silvia di Luise

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 21:05:18