JSON Schema验证:子Schema中proto为HTTPS_TERM时根subdomains需存在对应name条目
校验规则实现结论
你描述的校验规则完全可以通过JSON Schema实现,推荐使用JSON Schema Draft 2019-09及以上版本,配合主流校验工具(比如Ajv)即可无需额外自定义代码完成校验。
实现逻辑说明
- 先定义基础字段的常规格式校验:比如
endpoints、subdomains的数组类型要求,每个子字段的类型、必填规则等 - 核心关联校验逻辑:遍历所有
endpoints下的ports元素,当检测到proto为HTTPS_TERM时,强制校验根节点subdomains数组中存在name与当前port的name完全匹配的条目
完整校验Schema代码
{ "$schema": "https://json-schema.org/draft/2019-09/schema", "type": "object", "required": ["endpoints", "subdomains"], "properties": { "endpoints": { "type": "array", "items": { "type": "object", "required": ["ip_name", "ip", "ports"], "properties": { "ip_name": { "type": "string" }, "ip": { "type": "string", "format": "ipv4" }, "ports": { "type": "array", "items": { "type": "object", "required": ["name", "port", "proto"], "properties": { "name": { "type": "string" }, "port": { "type": "integer", "minimum": 1, "maximum": 65535 }, "proto": { "type": "string" } }, "allOf": [ { "if": { "properties": { "proto": { "const": "HTTPS_TERM" } } }, "then": { "properties": { "name": { "in": { "$data": "/subdomains/*/name" } } } } } ] } } } } }, "subdomains": { "type": "array", "items": { "type": "object", "required": ["name", "value"], "properties": { "name": { "type": "string" }, "value": { "type": "string" } } } } } }
注:如果你使用的校验工具不支持Draft 2019-09的
$data和in关键字,也可以通过校验工具提供的自定义规则能力实现,逻辑和上面的判断规则完全一致。你提供的两个合法示例用上述Schema校验都会正常通过。
内容的提问来源于stack exchange,提问作者Zili
相关产品推荐
相关产品推荐

