如何实现基于newPrices数组长度的thresholds属性条件必填?
解决方案(JSON Schema Draft-04)
要实现「当newPrices数组元素数量大于1时,thresholds为必填项」的逻辑,由于Draft-04不支持if/then关键字,我们可以通过allOf结合not/required构建条件约束,具体修改如下:
修改要点
- 调整基础必填规则:将
prices.items下的required数组从["newPrices", "thresholds"]改为仅["newPrices"],因为thresholds不再是全局必填项。 - 添加条件约束:通过
allOf引入额外规则,禁止出现「newPrices长度大于1且未提供thresholds」的非法情况。
修改后的完整Schema
{ "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "required": [ "id" ], "properties": { "id": { "type": "string", "maxLength": 50, "minLength": 1, "title": "ID", "readOnly": true }, "description": { "type": "string", "nullable": true, "title": "Description" }, "allItems": { "type": "array", "title": "All Items", "items": { "required": [ "prices" ], "type": "object", "properties": { "prices": { "type": "array", "maxItems": 8, "title": "Test Prices", "items": { "required": [ "newPrices" ], "type": "object", "properties": { "newPrices": { "type": "array", "title": "New Prices", "maxItems": 4, "minItems": 1, "items": { "type": "number", "format": "double" } }, "thresholds": { "type": "array", "maxItems": 3, "title": "Thresholds", "items": { "type": "integer", "format": "int32" } } }, "additionalProperties": false, "allOf": [ { "not": { "allOf": [ { "properties": { "newPrices": { "minItems": 2 } }, "required": ["newPrices"] }, { "not": { "required": ["thresholds"] } } ] } } ] } } }, "additionalProperties": false }, "nullable": true } }, "additionalProperties": false }
逻辑说明
- 当
newPrices长度=1时:thresholds可省略,符合基础规则; - 当
newPrices长度>1时:not关键字会排除「未提供thresholds」的情况,强制要求thresholds必须存在。
内容的提问来源于stack exchange,提问作者TomTommyTom
相关产品推荐
相关产品推荐

