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

如何使用JSON Schema根据my_type值要求对应子属性必须存在?

JSON Schema嵌套属性依赖校验解决方案

你需要利用JSON Schema的if/then条件关键字,结合嵌套的属性约束来实现需求。以下是修改后的完整Schema:

{
    "type": "object",
    "properties": {
        "my_type": {
            "type": "string"
        },
        "t1_data": {
            "type": "object",
            "properties": {
                "id": {
                    "type": "string"
                }
            }
        },
        "t2_data": {
            "type": "object",
            "properties": {
                "id": {
                    "type": "string"
                }
            }
        }
    },
    "allOf": [
        {
            "if": {
                "properties": {
                    "my_type": {
                        "const": "type1"
                    }
                },
                "required": ["my_type"]
            },
            "then": {
                "properties": {
                    "t1_data": {
                        "required": ["id"]
                    }
                },
                "required": ["t1_data"]
            }
        },
        {
            "if": {
                "properties": {
                    "my_type": {
                        "const": "type2"
                    }
                },
                "required": ["my_type"]
            },
            "then": {
                "properties": {
                    "t2_data": {
                        "required": ["id"]
                    }
                },
                "required": ["t2_data"]
            }
        }
    ]
}

规则说明

  • 当my_type等于"type1"时:if条件匹配,then块会强制要求t1_data必须存在,且t1_data的id属性为必填项
  • 当my_type等于"type2"时:第二个if条件匹配,then块强制要求t2_data必须存在,且t2_data的id属性为必填项
  • 当my_type为其他值或未提供时:两个if条件都不触发,无额外校验约束,直接通过校验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 06:40:47