json - JSON 模式中的条件检查
问题描述
我有以下 JSON 模式:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"additionalProperties": false,
"properties": {
"Payload": {
"type": "object",
"additionalProperties": false,
"properties": {
"Person": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"properties": {
"Id": {
"type": "string"
},
"Name": {
"type": "string"
}
},
"required": [
"Id",
"Name"
]
}
}
}
},
"Reference": {
"type": "object",
"additionalProperties": false,
"properties": {
"Status": {
"anyOf": [
{
"Passed": {
"type": "string"
},
"Failed": {
"type": "string"
}
}
]
}
}
}
},
"anyOf": [
{
"additionalProperties": false,
"properties": {
"Status": {
"type": "string",
"enum": [
"Failed"
]
}
},
"required": [
"Reference"
],
"not": {
"required": [
"Payload"
]
}
},
{
"additionalProperties": true,
"properties": {
"Status": {
"type": "string",
"enum": [
"Passed"
]
}
},
"required": [
"Reference"
]
}
]
}
我想检查 JSON 消息的状态是否失败,那么人员数组不应该存在。仅当状态通过时才应存在。
我在这里尝试了以下解决方案,但是当验证器通过失败状态和人员详细信息时,我肯定做错了。有人可以告诉我可能做错了什么吗?
解决方案
你有几个问题。
/属性/参考/属性/状态
这不是有效的架构。看起来您正在尝试描述一个枚举。
附加属性
原因很复杂,但条件模式不适用于additionalProperties
. 好消息是它也是不必要的。你可以把那些排除在外。
/任何
看起来您正在使用“枚举”模式,但在这种情况下暗示模式更好,因为只有一个枚举状态具有额外的约束。
以嵌套属性为条件
您定义Reference.Status
值的模式实际上只是指向Status
. 您还需要一个描述父属性的模式。
以下是我认为您的架构试图做的事情。
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"additionalProperties": false,
"properties": {
"Payload": {
"type": "object",
"additionalProperties": false,
"properties": {
"Person": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"properties": {
"Id": { "type": "string" },
"Name": { "type": "string" }
},
"required": ["Id", "Name"]
}
}
}
},
"Reference": {
"type": "object",
"additionalProperties": false,
"properties": {
"Status": { "enum": ["Passed", "Failed"] }
}
}
},
"anyOf": [
{
"not": {
"properties": {
"Reference": {
"properties": {
"Status": { "enum": ["Failed"] }
},
"required": ["Status"]
}
},
"required": ["Reference"]
}
},
{ "not": { "required": ["Payload"] } }
]
}
推荐阅读
- python - 如何在特定列包含子字符串时有效地删除数据框中的行
- wpf - 具有绑定选定值和静态项的 WPF 组合框在初始化时无法识别选择
- swift - SceneKit – SCNMatrix4 中的最低行元素是做什么用的?
- python - Python,PIP,线分析器的构建轮失败
- python - PyQt5 StackedWidget首页边框图片不起作用
- php - 如何按发送日期订购短信
- python - 对依赖于数据库的函数进行单元测试
- mysql - 连接两个或多个表时的 SQL 查询
- javascript - 当我在角度 5 中将令牌作为参数传递时,无法匹配任何路由
- django - 如何从 django admin 中添加外键关系