json - JSON Schema oneOf 验证
问题描述
我正在尝试创建一个 JSON 模式,它允许属性是数字或特定格式的对象。
我的数据如下所示:
{
"num": 200
}
我的架构看起来像这样:
{
"properties": {
"num": {
"type": [
"number",
"object"
],
"oneOf": [
{
"type": "number"
},
{
"$ref": "#/definitions/Variable"
}
]
}
},
"required": [
"num"
],
"additionalProperties": false,
"definitions": {
"Variable": {
"title": "Variable",
"properties": {
"$variable$": {
"type": "boolean",
"example": true
},
"name": {
"type": "string"
},
"defaultValue": {
"type": [
"string",
"object",
"number"
]
}
},
"required": [
"$variable$",
"name"
],
"additionalProperties": false
}
}
}
当我在这里通过验证器运行它时:https ://www.jsonschemavalidator.net/
我收到此错误:
Message: JSON is valid against more than one schema from 'oneOf'. Valid schema indexes: 0, 1.
Schema path: #/properties/num/oneOf
我假设我错过了一些关于如何oneOf
工作的明显内容,但我无法弄清楚它可能是什么。在此不胜感激,谢谢!
解决方案
你得到的错误是告诉你你们两个oneOf
模式都验证为真。令人惊讶的是,该值4
对以下模式有效。
{
"properties": {
"foo": { "type": "string": }
},
"required": ["foo"]
}
事实证明,当值不是对象时,properties
关键字和required
关键字不适用。{}
因此,在针对数字(或任何非对象)进行验证时,上述模式实际上是空模式 ( )。因为空模式意味着没有约束,所以一切都是有效的。
要解决您的问题,只需添加"type": "object"
到您的/definitions/Variable
架构中。
推荐阅读
- networking - 如何在 GNS3 中将 FastEthernet 端口添加到以太网交换机?
- windows - MSVC 中的自定义构建步骤和自定义构建工具
- r - 在 R 中使用 lubridate make_datetime 后未知的日期列类
- c++ - 是否可以让 CTAD 接受模板类型别名?
- javascript - 如何从 Firebase 身份验证获取 Twitter 用户名 - Javascript
- apache-flink - 在哪里存储 Apache Flink SQL 的凭据和其他机密?
- python - 包含具有相同外键的相关对象的查询集
- angular - 为什么 getter 有时会在模板中触发?
- list - 使用 ansible 访问字典文件的 yaml 列表
- mysql - 从表 A 中选择,并将其设置在表 B 中不存在的值自定义 JPA 查询