如何为不同父对象的引用Schema设置差异化必填字段?
实现JSON Schema中不同父对象下的组件字段必填差异
要达成你需要的效果,只需给software字段的定义使用allOf关键字,先复用基础的component schema,再额外添加version的必填要求即可,修改后的完整Schema如下:
{ "$schema": "http://json-schema.org/draft-07/schema#", "properties": { "metadata": { "$ref": "#/definitions/metadata", "title": "Metadata", "description": "Provides additional information about a ABC." } }, "definitions": { "metadata": { "type": "object", "title": "BOM Metadata Object", "properties": { "software": { "title": "Software", "description": "The component that the ABC describes.", "allOf": [ {"$ref": "#/definitions/component"}, {"required": ["version"]} ] }, "tool" : { "items": {"$ref": "#/definitions/component"} } } }, "component": { "type": "object", "title": "Component Object", "required" : ["name"], "properties": { "name": { "type": "string", "title": "Component Name" }, "version": { "type": "string", "title": "Component Version" } } } } }
关键修改说明
- software字段:通过
allOf组合两条规则,第一条引用基础component(自带name必填要求),第二条新增version为必填项,叠加后software就同时要求name和version都必填。 - tool字段:保持原有引用方式,因此其中的每个component仍然仅要求
name必填,完全匹配你的需求。
内容的提问来源于stack exchange,提问作者Ravi Trivedi
相关产品推荐
相关产品推荐

