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

如何根据header的messageType值约束JSON Schema的body必填字段?

解决方案:基于JSON Schema的消息体条件验证

下面是符合需求的JSON Schema实现,通过definitions实现规则复用与扩展,结合allOf+if/then完成跨字段条件校验:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "required": ["header", "body"],
  "properties": {
    "header": {
      "type": "object",
      "required": ["messageType"],
      "properties": {
        "messageType": {
          "type": "string",
          "enum": ["message1", "message2"]
        }
      }
    },
    "body": {
      "type": "object"
    }
  },
  "definitions": {
    "message1Body": {
      "required": ["prop1"],
      "properties": {
        "prop1": {
          "type": "string"
        }
      }
    },
    "message2Body": {
      "required": ["prop2"],
      "properties": {
        "prop2": {
          "type": "integer"
        }
      }
    }
  },
  "allOf": [
    {
      "if": {
        "properties": {
          "header": {
            "properties": {
              "messageType": {
                "const": "message1"
              }
            },
            "required": ["messageType"]
          }
        }
      },
      "then": {
        "properties": {
          "body": {
            "$ref": "#/definitions/message1Body"
          }
        }
      }
    },
    {
      "if": {
        "properties": {
          "header": {
            "properties": {
              "messageType": {
                "const": "message2"
              }
            },
            "required": ["messageType"]
          }
        }
      },
      "then": {
        "properties": {
          "body": {
            "$ref": "#/definitions/message2Body"
          }
        }
      }
    }
  ]
}

关键说明

  • definitions区块:将不同消息类型对应的body校验规则独立封装,后续新增message3等类型时,只需在definitions中添加新的body规则,再在allOf中补充对应if/then分支即可,完全满足扩展需求。
  • 跨字段校验实现:if条件通过嵌套的properties结构精准定位到header.messageType的取值(用const做精确匹配),then分支通过$ref引用对应的body规则,确保当messageType为指定值时,body必须包含对应字段。
  • 兼容性:示例采用JSON Schema Draft 07标准,if/then和const均为该版本的标准特性,兼容绝大多数主流JSON验证库。

可选配置

如果需要限制body只能包含指定字段(禁止额外属性),可在definitions的body规则中添加"additionalProperties": false,例如:

"message1Body": {
  "required": ["prop1"],
  "properties": {
    "prop1": {
      "type": "string"
    }
  },
  "additionalProperties": false
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 16:46:08