如何在JSON Schema中实现XML Schema的keyref等效功能?
问题描述
我正尝试为如下结构的JSON数据创建JSON Schema:
{ "equipments": { "A": {}, "B": {} }, "work": [ { "equipment": "A" } ] }
当前使用的Schema如下:
{ "$id": "example", "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": { "equipments":{ "type": "object", "additionalProperties": true }, "work": { "type": "array", "items": { "type": "object", "properties": { "equipment": { "type": "string" } } } } } }
equipments对象中配置了不同的设备,work数组中的项需要引用这些设备。在XML Schema中我会使用keyref实现此功能,但未找到JSON Schema中的等效方案,请问是否存在等效方案,还是JSON Schema不支持该功能?
解决方案
JSON Schema从Draft 2019-09版本开始支持类似XML Schema中keyref的引用验证功能,主要有两种实现方式:
方式一:使用$data关键字动态绑定设备键名
$data关键字可以直接引用JSON实例中的其他值来定义约束,让work数组内的equipment字段值必须匹配equipments对象的键名:
{ "$id": "example", "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": { "equipments": { "type": "object", "additionalProperties": true, "propertyNames": { "type": "string" } }, "work": { "type": "array", "items": { "type": "object", "properties": { "equipment": { "type": "string", "$data": "/equipments" } }, "required": ["equipment"] } } }, "required": ["equipments", "work"] }
这里"$data": "/equipments"表示equipment字段的值必须是equipments对象的有效键名之一。
方式二:使用$dynamicRef复用设备键约束
如果需要在多个字段复用设备键的验证规则,可以结合$dynamicRef和propertyNames定义可引用的约束片段:
{ "$id": "example", "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": { "equipments": { "type": "object", "additionalProperties": true, "propertyNames": { "$id": "#equipment-key" } }, "work": { "type": "array", "items": { "type": "object", "properties": { "equipment": { "$dynamicRef": "#equipment-key" } }, "required": ["equipment"] } } }, "required": ["equipments", "work"] }
这种方式将设备键的验证规则封装为可引用的片段,后续其他字段需要验证设备键时,直接通过$dynamicRef引用即可。
注意:部分JSON Schema验证工具可能未完全兼容$data或$dynamicRef,使用前请确认工具对Draft 2019-09及以上版本的支持情况。
内容的提问来源于stack exchange,提问作者bortgerres
相关产品推荐
相关产品推荐

