我在模式中定义了validType
,其中每个属性都应具有text
和annotation
。
我想添加其他约束以细化text
的course
,必须遵循"pattern":"[a-z]{2}[0-9]{2}"
。有什么方法可以直接应用约束而无需复制并粘贴validType
的内容?
模式:
{
"type": "object",
"definition": {
"validType": {
"description": "a self-defined type, can be complicated",
"type": "object",
"properties": {
"text": {
"type": "string"
},
"annotation": {
"type": "string"
}
}
},
"properties": {
"name": {
"$ref": "#/definitions/validType"
},
"course": {
"$ref": "#/definitions/validType"
}
}
}
}
数据:
{"name":{
"text":"example1",
"annotation":"example1Notes"},
"course":{
"text":"example2",
"annotation":"example2Notes"}}
course
的预期模式应按以下方式工作:
{"course": {
"type": "object",
"properties": {
"text": {
"type": "string",
"pattern":"[a-z]{2}[0-9]{2}"
},
"annotation": {
"type": "string"
}
}
}}
但是不要重复有效的大块代码,我期望类似于下面的格式:
{"course": {
"$ref": "#/definitions/validType"
"text":{"pattern":"[a-z][0-9]"}
}}
是的!您可以添加约束,但不能修改引用的约束。
要添加约束,您需要了解草稿07和先前版本的$ref
是子模式中唯一允许存在的键。其他键(如果存在)将被忽略。
因此,您需要创建两个子方案,其中一个具有参考性,另一个则具有其他约束。然后,将这两个子方案包装在allOf
中。
这是什么样子...
{
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"course": {
"allOf": [
{
"$ref": "#/definitions/validType"
},
{
"properties": {
"text": {
"pattern": "[a-z][0-9]"
}
}
}
]
}
}
}
使用https://jsonschema.dev进行播放