【发布时间】:2019-11-09 06:50:49
【问题描述】:
我的 JSON 验证有问题。我的页面中有 3 个链接的选择框,我需要验证以反映 UI 显示的内容。
3个选择是:
- 范围:可以是ScopeNational、ScopeRegional或ScopeInternational
- 国家:国家列表
- 地区:地区列表(“欧洲”、“亚洲”等)
在模式中,选择是具有两个属性的对象:“key”和“text”,都是字符串。
如果范围是“ScopeNational”,则需要“Country”和“Region”。如果范围是“ScopeRegional”,则只需要“Region”。最后,如果范围是“ScopeInternational”,则不需要“Country”或“Region”。
我用anyOf、oneOf 和if-then-else 尝试了许多配置,但我无法实现
这是我尝试的最后一个架构,但没有成功:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "http://example.com/root.json",
"type": "object",
"title": "Linked scope",
"default": null,
"properties": {
"scope": {
"$id": "#/properties/scope",
"title": "Project scope",
"$ref": "#/definitions/Scope"
},
"country": {
"$id": "#/properties/country",
"title": "Country",
"$ref": "#/definitions/Choice"
},
"region": {
"$id": "#/properties/region",
"title": "Region",
"$ref": "#/definitions/Choice"
}
},
"oneOf": [
{
"properties": {
"scope": {
"properties": {
"key": {
"const": "ScopeNational"
}
}
},
"country": {
"required": [
"key",
"text"
]
},
"region": {
"required": [
"key",
"text"
]
}
}
},
{
"properties": {
"scope": {
"properties": {
"key": {
"const": "ScopeRegional"
}
}
},
"region": {
"required": [
"key",
"text"
]
}
}
},
{
"properties": {
"scope": {
"properties": {
"key": {
"const": "ScopeInternational"
}
}
}
}
}
],
"required": [
"scope"
],
"definitions": {
"Choice": {
"type": "object",
"properties": {
"key": {
"type": "string"
},
"text": {
"type": "string"
}
},
"required": [
"key",
"text"
]
},
"Scope": {
"type": "object",
"properties": {
"key": {
"type": "string",
"enum": [
"ScopeNational",
"ScopeRegional",
"ScopeInternational"
]
},
"text": {
"type": "string"
}
},
"required": [
"key",
"text"
]
}
}
}
谢谢!
【问题讨论】:
-
能否给我们展示一个有效和无效的 JSON 示例?
-
@leadpony 绝对是 这将是有效的:
json { "scope": { "key": "ScopeNational", "text": "National" }, "country": { "key": "France", "text": "France" }, "region": { "key": "Europe", "text": "Europe" } }这不会:json { "scope": { "key": "ScopeNational", "text": "National" }, "country": { "key": null, "text": null }, "region": { "key": "Europe", "text": "Europe" } }