如何从 json 架构中的值获取类型引用
how to get type reference from value in json schema
我有一个 json 架构,我有 3 种类型的媒体、标题、图像和头像。
每种媒体类型都有不同的结构,因此我使用 $ref
和 oneOf
来指定哪些是有效选项。
但是,我不知道如何根据同级的值指定使用哪个 ref。
我的架构如下所示
const mediaSchema = {
"type": "object",
"required": ["mediaType", "content", "points"],
"properties":{
"mediaType": {"type":"string", "pattern": "^(image|avatar|caption)$"},
"content": {
"oneOf": [
{"$ref":"#/definitions/image"},
{"$ref": "#/definitions/caption"},
{"$ref": "#/definitions/avatar"}
],
}
},
"definitions": {
"caption":
{"type": "object",
"required": ["text"],
"properties": {
"text": {"type": "string"},
"fontSize": {"type": "string", "pattern": "^[0-9]{1,3}px$"}
}
},
"image": {"type": "string", "format": "url"},
"avatar":
{"type": "object",
"properties": {
"name": {"type": "string"},
"image": {"type": "string", "format":"url"}
}
}
}
}
当我定义一个头像时
mediaItem = {
"mediaType":"avatar",
"content": {
"name": "user name",
"avatar": "https://urlToImage
}
}
应该是有效的,但是如果我定义一个头像为
mediaItem = {
"mediaType": "avatar",
"content": "https://urlToImage"
}
它应该抛出一个错误,因为它对头像的媒体类型无效。
你走在正确的轨道上,但你应该将 oneOf 调度程序放在模式的根部,并用 3 个单独的常量定义 "content"
作为鉴别器,如下所示:
{
"oneOf": [
{
"type": "object",
"properties": {
"mediaType": {
"const": "avatar"
},
"content": { "$ref": "#/definitions/avatar" }
},
"required": ["mediaType", "content"]
},
// ...
],
"definitions": {
// ...
}
}
注意:"const"
关键字仅存在于最新版本的 json 架构(draft6)中。您使用的验证器实现可能还不支持它。在这种情况下,您可以将 "const": "avatar"
替换为单元素枚举,例如 "enum": ["avatar"]
我有一个 json 架构,我有 3 种类型的媒体、标题、图像和头像。
每种媒体类型都有不同的结构,因此我使用 $ref
和 oneOf
来指定哪些是有效选项。
但是,我不知道如何根据同级的值指定使用哪个 ref。
我的架构如下所示
const mediaSchema = {
"type": "object",
"required": ["mediaType", "content", "points"],
"properties":{
"mediaType": {"type":"string", "pattern": "^(image|avatar|caption)$"},
"content": {
"oneOf": [
{"$ref":"#/definitions/image"},
{"$ref": "#/definitions/caption"},
{"$ref": "#/definitions/avatar"}
],
}
},
"definitions": {
"caption":
{"type": "object",
"required": ["text"],
"properties": {
"text": {"type": "string"},
"fontSize": {"type": "string", "pattern": "^[0-9]{1,3}px$"}
}
},
"image": {"type": "string", "format": "url"},
"avatar":
{"type": "object",
"properties": {
"name": {"type": "string"},
"image": {"type": "string", "format":"url"}
}
}
}
}
当我定义一个头像时
mediaItem = {
"mediaType":"avatar",
"content": {
"name": "user name",
"avatar": "https://urlToImage
}
}
应该是有效的,但是如果我定义一个头像为
mediaItem = {
"mediaType": "avatar",
"content": "https://urlToImage"
}
它应该抛出一个错误,因为它对头像的媒体类型无效。
你走在正确的轨道上,但你应该将 oneOf 调度程序放在模式的根部,并用 3 个单独的常量定义 "content"
作为鉴别器,如下所示:
{
"oneOf": [
{
"type": "object",
"properties": {
"mediaType": {
"const": "avatar"
},
"content": { "$ref": "#/definitions/avatar" }
},
"required": ["mediaType", "content"]
},
// ...
],
"definitions": {
// ...
}
}
注意:"const"
关键字仅存在于最新版本的 json 架构(draft6)中。您使用的验证器实现可能还不支持它。在这种情况下,您可以将 "const": "avatar"
替换为单元素枚举,例如 "enum": ["avatar"]