如何按组引用自定义类型而非逐个单独引用?
问题
如何按组引用类型而非逐个单独引用?例如,希望sum和subtract类型仅接受number相关类型(number、sum、subtract),而concatenate类型可同时接受number和string相关类型(包含自身)。当新增类型时,希望能自动将其纳入对应分组。
解决方案
你可以通过在JSON Schema的definitions中定义分组类型来实现按组引用,避免手动逐个添加引用项,后续新增类型时只需更新分组定义即可。具体实现如下:
- 在
definitions中预先定义两个分组:NumberRelated:统一管理所有数值相关类型(基础number、sum、subtract等)StringNumberRelated:管理字符串+数值混合类型(基础number/string、sum、subtract、concatenate等)
- 各个具体类型的规则中,直接引用对应分组的定义,无需重复罗列每个类型引用
- 新增类型时,仅需将新类型的
$ref加入对应分组,所有引用该分组的位置会自动生效
以下是修改后的完整Schema:
{ "definitions": { // 数值相关类型分组 "NumberRelated": { "anyOf": [ { "type": "number" }, { "$ref": "#/definitions/sum" }, { "$ref": "#/definitions/subtract" } ] }, // 字符串+数值混合类型分组 "StringNumberRelated": { "anyOf": [ { "type": "number" }, { "type": "string" }, { "$ref": "#/definitions/sum" }, { "$ref": "#/definitions/subtract" }, { "$ref": "#/definitions/concatenate" } ] }, "sum": { "title": "sum", "type": "object", "properties": { "values": { "type": "array", "items": { "$ref": "#/definitions/NumberRelated" } } }, "required": ["values"] }, "subtract": { "title": "subtract", "type": "object", "properties": { "minuend": { "$ref": "#/definitions/NumberRelated" }, "subtrahend": { "$ref": "#/definitions/NumberRelated" } }, "required": ["minuend", "subtrahend"] }, "concatenate": { "title": "concatenate", "type": "object", "properties": { "strings": { "type": "array", "items": { "$ref": "#/definitions/StringNumberRelated" } } }, "required": ["strings"] } }, "title": "Step", "type": "object", "properties": { "value": { "$ref": "#/definitions/NumberRelated" } } }
比如后续新增multiply数值类型,只需在NumberRelated的anyOf中添加{ "$ref": "#/definitions/multiply" },所有引用该分组的规则会自动包含这个新类型。
内容的提问来源于stack exchange,提问作者eSPiYa
相关产品推荐
相关产品推荐

