JSON Schema 2020-12版对象数组中enum枚举验证不生效问题
问题根源
你写的两份Schema存在相同的结构错误:main字段是对象类型,你把它下属的items数组的校验规则直接写在了main的properties节点同级,这个位置的items关键字仅对数组类型的节点生效,对对象类型节点完全无效,所以数组元素的校验规则从未被执行,自然不会抛出错误。
修正方案
把main下的items数组的定义挪到main的properties节点内部即可,以下是修正后的完整Schema(基于写法1修改):
{ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://example.com/schema.json", "$defs": { "my_shiny_object": { "type": "object", "required": [ "attribute1" ], "properties": { "attribute1": { "description": "This is mandatory attribute 1 with an enum", "type": "string", "enum": [ "Option 1", "Option 2", "Option 3" ] }, "attribute2": { "type": "string", "description": "This is an optional attribute 2" } } } }, "title": "root", "description": "Root Element.", "type": "object", "required": [ "main" ], "properties": { "main": { "type": "object", "title": "main", "description": "Main is the top level field.", "required": [ "items" ], "properties": { "date_time": { "type": "string", "format": "date-time", "title": "Date/time optional", "description": "Date time" }, "items": { "type": "array", "description": "Items included in main", "items": { "$ref": "#/$defs/my_shiny_object" } } } } } }
修改后再测试,当attribute1缺失、取值不在枚举范围内时都会正常抛出校验错误。
内容的提问来源于stack exchange,提问作者user1452030
相关产品推荐
相关产品推荐

