如何使用JSON Schema检查字符串数组的元素数量是否为奇数?
能否用JSON Schema检查字符串数组的元素数量是否为奇数?
可以实现,不过需要依赖JSON Schema Draft 7及以上版本支持的$expr关键字(主流验证器如AJV均支持该特性),也可以通过组合关键字的方式兼容部分旧版本。以下是两种可行方案:
方案一:使用$expr表达式校验(推荐)
利用$expr编写表达式判断数组长度对2取余不等于0,同时确保数组元素均为字符串:
{ "type": "object", "properties": { "list": { "type": "array", "items": { "type": "string" }, "$expr": { "$ne": [ { "$mod": [ { "$size": "list" }, 2 ] }, 0 ] } } }, "required": ["list"] }
方案二:组合关键字实现(兼容旧版本)
通过contains和not组合间接判断数组长度为奇数,该方案仅适用于数组元素非空的场景:
{ "type": "object", "properties": { "list": { "type": "array", "items": { "type": "string" }, "minItems": 1, "not": { "contains": {}, "contains": {} } } }, "required": ["list"] }
验证示例
有效示例1
{ "list": [ "one", "two", "three" ] }
有效示例2
{ "list": [ "one", "two", "three", "four", "five" ] }
无效示例
{ "list": [ "one", "two", "three", "four" ] }
内容的提问来源于stack exchange,提问作者ghaschel
相关产品推荐
相关产品推荐

