json - JSON Schema `required` 允许空字符串作为值
问题描述
我正在使用 JSON 模式模板来验证在线表单接收到的数据。验证器的要求之一是它允许根据对其他问题给出的答案提出一些问题。
例如,如果问题是Do you want a loan?
并且用户回答yes
,则What is the loan to be used for?
需要将问题的答案设置为 required ,以便用户必须提供答案。如果答案是no
,则不需要第二个问题。
我正在使用定义来定义我的问题,然后在下面的主要问题模式中引用它们。我读到,通过使用 draft-07 中提供的 if-then-else 功能,我可以使用它来根据其他问题的答案设置某些需要回答的问题。
在这种特殊情况下,我希望发生的是,如果用户输入Home improvements (General)
问题 9 的答案,那么问题 257 将设置为必需并且必须回答,否则应该抛出错误。
目前,当我将此验证器输入https://www.jsonschemavalidator.net/时,它无法按预期工作。实际发生的情况是问题 257 的答案可以留空,即使问题 9 的答案是“家居改善(一般)
如何更改我的架构以提供我想要获得的行为?
JSON 模式
{
"$schema": "http://json-schema.org/draft-07/schema#",
"definitions": {
"question3-9": {
"type": "object",
"properties": {
"answer": {
"type": "string",
"enum": [
"Home improvements (General)",
"Other"
]
}
}
},
"question3-257": {
"type": "object",
"properties": {
"answer": {
"type": "string",
}
}
}
},
"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"
}
},
"if": {
"properties": {
"9": {
"properties": {
"answer": {
"enum": [
"Home improvements (General)"
]
}
}
}
}
},
"then": {
"required": [
"257"
]
}
}
}
}
},
"required": [
"3"
]
}
}
}
}
}
要验证的 JSON:
{
"form_submission": {
"sections": {
"3": {
"questions": {
"9": {
"answer": "Home improvements (General)",
},
"257": {
"answer": "",
}
}
}
}
}
}
更新了如果-那么
"if": {
"properties": {
"9": {
"properties": {
"answer": {
"enum": [
"Home improvements (General)"
]
}
},
"required": ["answer"]
}
},
"required": ["9"]
},
"then": {
"257": {
"properties":{
"answer":{
"minLength": 1
}
}
}
}
解决方案
您的问题是您希望required
检查密钥的值,而事实并非如此。
当前草案 7 规范要求:
如果数组中的每个项目都是实例中属性的名称,则对象实例对该关键字有效。
这意味着required
只检查对象的密钥是否存在。它与价值无关。对于字符串验证,请参阅适用于字符串的验证关键字。我怀疑你想要minLength
或pattern
(这是正则表达式)。
https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-6.3
推荐阅读
- javascript - javascript数组循环到表
- hadoop - Windows 上的 Hadoop 安装:无法为您的平台加载 native-hadoop 库...在适用的情况下使用内置 java 类
- node.js - 使用 nodejs 在 RHEL linux 上安装连接 Web 服务器
- javascript - 有没有办法改变我在 find() 函数中比较的字段的值?
- docker - 在 docker build 期间重新加载 Nginx
- debian - udev 规则中的无条件 GOTO(和 Medion RC-0617)
- java - Java 中的 String 是如何成为引用类型的?
- php - 自定义 Laravel Backpack for Datatables 的 HTML 搜索响应
- php - 使用 PHP HTML Parser 将 HTML 附加到标签
- android - 如何识别 FCM 消息是针对 FCM 客户端处理程序还是 UrbanAirship 处理程序