JsonSchema:基于其他属性值验证类型的技术问询
实现基于其他属性值的动态JSON Schema验证
要实现根据其他属性值来动态调整验证规则,你可以使用JSON Schema(draft-07及以上版本)提供的if/then/else关键字——这是处理这类条件验证场景的标准方案。结合你现有的规则Schema,我来给你具体的实现指导和示例:
核心思路
我们要给conditions数组中的每个条件项添加逻辑:
- 当
field为"Name"时,relation只能是字符串相关的操作(比如忽略大小写包含、完全匹配等),且value必须是字符串类型 - 当
field为"Size"时,relation只能是数值比较操作(比如大于、小于等),且value必须是数字类型
完整的Schema示例
{ "$schema": "http://json-schema.org/draft-07/schema#", "title": "Rules", "description": "Describes a set of rules", "type": "object", "properties": { "rules": { "type": "array", "items": { "type": "object", "properties": { "precedence": { "type": "number", "minimum": 0 }, "conditions": { "type": "array", "items": { "type": "object", "required": ["field", "relation", "value"], "properties": { "field": { "type": "string", "enum": ["Name", "Size"] }, "relation": { "type": "string" }, "value": { "type": ["string", "number"] } }, // 条件验证逻辑:根据field的值动态约束relation和value "if": { "properties": { "field": { "const": "Name" } } }, "then": { "properties": { "relation": { "enum": ["containsIgnoreCase", "equals", "startsWith", "endsWith"] }, "value": { "type": "string" } } }, "else": { "if": { "properties": { "field": { "const": "Size" } } }, "then": { "properties": { "relation": { "enum": [">", "<", ">=", "<=", "==", "!="] }, "value": { "type": "number" } } } }, "additionalProperties": false } } }, "required": ["precedence", "conditions"], "additionalProperties": false } } }, "required": ["rules"], "additionalProperties": false }
关键部分解释
if/then/else逻辑:第一个if块检测field是否为"Name",满足时then块会强制relation只能是字符串操作枚举,且value必须是字符串;else块嵌套的if则处理field为"Size"的场景,约束relation为数值比较枚举、value为数字类型。required关键字:给每个条件项、外层规则项和根对象都添加了必填属性约束,保证结构完整性。additionalProperties: false:禁止出现Schema中未定义的额外属性,让验证更严格;如果需要允许额外属性,可以去掉这个配置。
版本兼容性说明
if/then/else是JSON Schema draft-07引入的特性,主流验证工具(如Ajv、JSON Schema Validator等)都已支持。如果必须使用更早版本,可以考虑用dependentSchemas处理简单依赖,但灵活性远不如if/then/else。
内容的提问来源于stack exchange,提问作者Joel Harris
相关产品推荐
相关产品推荐

