【发布时间】:2019-01-24 16:30:04
【问题描述】:
我有一个 JSON 提交,我正在尝试根据模板中定义的一些规则来验证它。此模板定义了向用户提出的许多问题。对于提交,是否需要其中一个问题的答案取决于上一个问题的值。
基本上
Do you have a dog? Yes/No
What kind of dog do you have?
第一个问题的有效答案使用枚举进行保护,因此用户只能提供yes 或no 字符串作为问题的答案。
如果用户对该问题的回答是肯定的,我希望第二个问题是必需的,这样如果当第一个答案是 yes 时第二个答案留空,则会引发错误。如果第一个答案是no,则用户可以将第二个问题留空。
以下是我目前拥有的 JSON 架构。
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"question3-9": {
"type": "object",
"properties": {
"answer": {
"type": "string",
"enum": [
"Yes", "No"
]
}
},
"if": {
"properties":{
"answer": {"enum": ["Yes"]}
}
},
"then": {"requried": "#/definitions/question3-257"}
},
"question3-257": {
"type": "object",
"properties": {
"answer": {
"type": "string",
"minLength": 1
}
}
}
},
"type": "object",
"properties": {
"form_submission": {
"type": "object",
"properties": {
"sections": {
"type": "object",
"properties": {
"3": {
"type": "object",
"properties": {
"questions": {
"type": "object",
"properties": {
"9": {
"$ref": "#/definitions/question3-9"
},
"257": {
"$ref": "#/definitions/question3-257"
}
},
"required": [
"257"
]
}
}
}
},
"required": [
"3"
]
}
}
}
}
}
我认为通过使用 JSON-Schema7 中可用的 if-then-else,我可以将第二个问题设置为 required,但它似乎不像这样工作。
这是使用上述架构验证的提交。
{
"form_submission": {
"sections": {
"3": {
"questions": {
"9": {
"answer": "Yes",
},
"257": {
"answer": "",
}
}
}
}
}
}
更新的 JSON 架构:
"3": {
"type": "object",
"properties": {
"questions": {
"type": "object",
"properties": {
"9": {
"$ref": "#/definitions/question3-9"
},
"257": {
"$ref": "#/definitions/question3-257"
}
},
"if": {
"properties":{
"answer": {"const": "Home improvements (General)"}
}
},
"then": {"required": ["257"]}
}
}
}
待验证:
"3": {
"questions": {
"9": {
"answer": "Home improvements (General)",
},
"257": {
"answer": "", //<-- This is an empty string but should be required since the answer to the abvoe question is "Home improvements (general) as defined with "answer": {"const": "Home improvements (General)"}
}
}
【问题讨论】:
标签: json jsonschema