如何让 jsonschema 使用假或属性的布尔值
How to get jsonschema to use a boolean of false OR attributes
我正在 json 架构中创建一个 Avatar
,在我的应用程序中,如果我们想隐藏头像,我们将其作为 false
传递,否则,头像有图像和名称。
在json模式中,我将头像指定为
const avatarSchema = {
"type": ["object", "boolean"],
"required": [],
"additionalProperties": false,
"properties":{
"name": {
"type": "string"
},
"image": {
"type": "string",
"format": "url"
}
}
};
这不起作用,因为如果 Avatar = true
、'image' does not exist on type 'Avatar'.
Property 'image' does not exist on type 'true'.
我不想Avatar
每一个都是true
,不是false
就是{image, name}
,我怎么告诉json schema来操作这条路?
您对架构为何不起作用的解释不正确。 required
、additionalProperties
和 properties
关键字仅在被验证的数据是对象时适用。因此,该架构应该可以按您希望的方式工作,除了它可以具有值 "true".
如果您使用的验证器给出了与您问题中的错误消息类似的错误消息,则它没有正确验证。您应该为该验证器提交错误报告。
无论如何,您的问题的解决方案需要 anyOf
关键字。
{
"anyOf": [
{ "enum": [false] },
{
"type": "object",
"required": ["name", "image"],
"additionalProperties": false,
"properties": {
"name": { "type": "string" },
"image": {
"type": "string",
"format": "url"
}
}
}
]
}
我正在 json 架构中创建一个 Avatar
,在我的应用程序中,如果我们想隐藏头像,我们将其作为 false
传递,否则,头像有图像和名称。
在json模式中,我将头像指定为
const avatarSchema = {
"type": ["object", "boolean"],
"required": [],
"additionalProperties": false,
"properties":{
"name": {
"type": "string"
},
"image": {
"type": "string",
"format": "url"
}
}
};
这不起作用,因为如果 Avatar = true
、'image' does not exist on type 'Avatar'.
Property 'image' does not exist on type 'true'.
我不想Avatar
每一个都是true
,不是false
就是{image, name}
,我怎么告诉json schema来操作这条路?
您对架构为何不起作用的解释不正确。 required
、additionalProperties
和 properties
关键字仅在被验证的数据是对象时适用。因此,该架构应该可以按您希望的方式工作,除了它可以具有值 "true".
如果您使用的验证器给出了与您问题中的错误消息类似的错误消息,则它没有正确验证。您应该为该验证器提交错误报告。
无论如何,您的问题的解决方案需要 anyOf
关键字。
{
"anyOf": [
{ "enum": [false] },
{
"type": "object",
"required": ["name", "image"],
"additionalProperties": false,
"properties": {
"name": { "type": "string" },
"image": {
"type": "string",
"format": "url"
}
}
}
]
}