如何在JSON Schema中定义符合指定Schema的预设可选对象属性?
解决方案
你可以用allOf关键字把枚举限制和schema验证结合起来,这样既要求值必须是枚举里的预设对象,又强制这些对象符合你定义的fruit schema规范。另外先纠正你现有schema里的一个错误:$defs.fruit中的properties应该是对象类型,不是数组,这是JSON Schema的语法要求。
具体实现步骤:
- 先修正
$defs里的fruitschema,把properties改成对象结构,确保它能正确验证水果对象的格式。 - 使用
allOf数组,同时包含enum(指定允许的预设对象)和$ref(引用fruit schema做格式验证)。这样枚举里的每个对象都会被自动校验是否符合fruit的规范,不符合的话整个schema会报错。
修正后的完整schema示例:
{ "$schema": "https://json-schema.org/draft/2020-12/schema", "description": "this is my favorite fruit", "allOf": [ { "enum": [ { "name": "apple", "color": "red" }, { "name": "banana", "color": "yellow" }, { "name": "oops, that's not a fruit", "taste": "fantastic" } ] }, { "$ref": "#/$defs/fruit" } ], "$defs": { "fruit": { "type": "object", "properties": { "name": { "type": "string" }, "color": { "type": "string" } }, "required": [ "name", "color" ], "unevaluatedProperties": false } } }
效果说明
- 验证数据时,输入值必须是
enum里的对象之一。 - 同时
enum里的每个对象都会被fruitschema校验:比如第三个对象缺少color属性、多了taste属性,会直接触发验证失败,能提前发现枚举里不符合规范的对象。
内容的提问来源于stack exchange,提问作者spettekaka
相关产品推荐
相关产品推荐

