如何在JSON Schema中允许多个同一类型对象实例
解决JSON Schema支持自定义键名同类型对象的问题
要实现允许任意数量、键名为自定义格式的同类型对象,你需要用JSON Schema的patternProperties关键字,它专门用来匹配符合正则表达式的键名,并定义对应值的结构。
核心配置示例
假设你的自定义键名都是类似component_xxx的格式(前缀为component_,后面跟任意字符),Schema可以这么写:
{ "type": "object", "patternProperties": { "^component_.*$": { "type": "object", "properties": { "id": {"type": "string"}, "type": {"type": "string"}, "config": {"type": "object"} }, "required": ["id", "type"] } }, // 如果只允许匹配patternProperties的键,不允许其他无关键,加上这行 "additionalProperties": false }
对应的合法JSON示例
{ "component_login_form": { "id": "login1", "type": "form", "config": {"submitText": "登录"} }, "component_user_card": { "id": "card2", "type": "card", "config": {"showAvatar": true} }, "component_any_name_here": { "id": "test3", "type": "chart" } }
为什么之前正则匹配没生效?
大概率是用错了关键字——如果之前把正则写在properties里是没用的,properties只接受固定字符串键名。必须用patternProperties来绑定正则和值类型。另外要注意正则的写法:
- 正则要符合JSON字符串的转义要求,比如如果正则里有
\,要写成\\(比如匹配数字的^component_\d+$要写成"^component_\\d+$") - 正则默认是匹配键名的全部内容,所以最好加上
^和$来确保完全匹配,避免部分匹配导致意外生效
扩展说明
如果你的JSON里除了这些自定义组件键,还允许其他固定键(比如metadata),可以同时用properties和patternProperties:
{ "type": "object", "properties": { "metadata": { "type": "object", "properties": {"version": {"type": "string"}} } }, "patternProperties": { "^component_.*$": { /* 组件结构定义 */ } }, // 允许metadata和匹配component_的键,其他键不允许 "additionalProperties": false }
内容的提问来源于stack exchange,提问作者nijj67
相关产品推荐
相关产品推荐

