【发布时间】:2017-12-06 13:01:20
【问题描述】:
我似乎无法弄清楚如何在 JSON 模式中实现某些目标。假设我有两个字段:status 和 quote。
条件依赖如下:
- 如果
status是["Y", "N"],那么quote是必需 - 如果
status是枚举中的任何其他内容,则quote不需要 - 如果
status不存在于 JSON 中,那么quote可以是任何东西
我正在尝试使用以下架构实现此行为:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"quote": {
"type": "string",
},
"status": {
"type": "string",
"enum": ["Y", "N", "M", "A", "S"]
}
},
"oneOf": [
{
"properties": {
"status": {"enum": ["Y", "N"]}
},
"required": [
"quote"
]
},
{
"properties": {
"status": {"enum": ["Y", "N", "M", "A", "S"]}
}
}
]
}
前两个条件按预期工作,但只要 JSON 中省略了 status 字段,验证就会失败。并且想要的行为是,只要status 字段不存在,我就可以拥有一个字段quote。
我怎样才能做到这一点?
更新
所以我设法实现了我最初提出的要求,但是,我现在有了额外的要求。也就是说,只要status 是["M", "A"],我就有一个额外的字段author,否则它只是可选的。如果status 不存在,则quote 和author 都可以是任何东西。我尝试如下:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"quote": { "type": "string" },
"author": { "type": "string" },
"status": { "enum": ["Y", "N", "M", "A", "S"] }
},
"allOf": [
{ "$ref": "#/definitions/y-or-n-requires-quote" },
{ "$ref": "#/definitions/m-or-a-requires-author" }
],
"definitions": {
"y-or-n-requires-quote": {
"anyOf": [
{ "not": { "$ref": "#/definitions/status-is-y-or-n" } },
{ "required": ["quote"] }
]
},
"m-or-a-requires-author": {
"anyOf": [
{ "not": { "$ref": "#/definitions/status-is-m-or-a" } },
{ "required": ["author"] }
]
},
"status-is-y-or-n": {
"properties": {
"status": { "enum": ["Y", "N"] }
}
},
"status-is-m-or-a": {
"properties": {
"status": { "enum": ["M", "A"] }
}
}
}
}
但是,对于不存在 status 的 JSON,使用此架构不起作用。
【问题讨论】:
标签: json jsonschema