如何用JSON Schema验证数组含至少一个指定枚举值且非空?
如何在JSON Schema中要求数组非空且包含指定枚举值?
我需要用JSON Schema验证对象中的favoriteVegetables数组,要求该数组至少包含carrot、lettuce、cucumber中的一个值(可包含任意或全部枚举值),但不能是空数组。
当前使用的Schema如下:
{ "$id": "https://www.example.com/vegetables.schema.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "Vegetables", "required": [ "favoriteVegetables" ], "type": "object", "properties": { "favoriteVegetables": { "type": "array", "items": { "type": "string", "enum": ["carrot", "lettuce", "cucumber"] } }, }, "additionalProperties": false }
现在的问题是这个Schema会允许favoriteVegetables为空数组[],请问该如何修改以添加“数组必须至少有一个元素”的验证规则?
只需在favoriteVegetables的数组配置中添加"minItems": 1即可。minItems是JSON Schema中专门用于限制数组最小元素数量的关键字,设置为1就能直接禁止空数组通过验证。结合原有的items枚举规则,就能同时满足“元素必须是指定蔬菜”和“数组非空”的要求。
修改后的完整Schema如下:
{ "$id": "https://www.example.com/vegetables.schema.json", "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "Vegetables", "required": [ "favoriteVegetables" ], "type": "object", "properties": { "favoriteVegetables": { "type": "array", "minItems": 1, "items": { "type": "string", "enum": ["carrot", "lettuce", "cucumber"] } } }, "additionalProperties": false }
内容的提问来源于stack exchange,提问作者Patrick Kenny
相关产品推荐
相关产品推荐

