c# - 如何使用 JSON Schema 将字符串值验证为 json 文本中的数字?
问题描述
我希望能够将答案字段验证为数值。下面的片段是一个答案,它是更大的答案字典的一部分。每个答案都遵循通用格式,因此需要答案字段为字符串类型。
"1": {
"answer": "80035",
"web_validated": true,
"web_error_string": "",
"server_error_string": ""
},
这会产生一个问题,因为我们使用 JSON Schema 来验证答案字典。我们需要将答案字段验证为数值,这是由字典必须遵守的 JSON 模板确定的。以下是字典中一个问题的上述答案的模板片段。
{
"id": "1",
"text": "KFI Number (Null required check)",
"type": "text",
"source": "phoebus",
"kfid_mapping": "KFID000",
"kfid_mapping_value": "",
"valid_answers": null,
"display_online": "readonly",
"required": "1",
"display_internal": "yes",
"hints": null,
"logic": null,
"rules": null,
"reason": null,
"conditional_explanation": null,
"conditional_question_id": null,
"conditional_question_answered": null,
"enabled": "1",
"order": "2",
"fk_section_id": "1",
"validated": false
}
我们用来验证问题 ID 的当前 JSON 模式:1。
"definitions": {
"question1-1": {
"type": "object",
"properties": {
"answer": {
"type": "string",
"minLength": 1
}
}
//other definitions removed
}
}
以上是此问题中显示的答案的 JSON 模式定义。
可能的解决方案:
- 将答案字段转换为数字字段,即去掉“” - 这确实有效,但它更昂贵并且是一种黑客行为。因此,在验证之前进行预处理。
- 只需将答案字段验证为字符串,不为空,不为空和最小长度检查。
我更愿意看看 JSON Schema 是否可行?
解决方案
正如其他人提到的,您可以使用模式。这是添加到您的示例的语法:
"definitions": {
"question1-1": {
"type": "object",
"properties": {
"answer": {
"type": "string",
"pattern": "^\d+$",
"description": "Use regex to validate this string as a series of one or more digits"
}
}
//other definitions removed
}
}
推荐阅读
- python - 在python中实现正则表达式时行继续后出现意外字符
- python - 尝试 konlpy,但出现与 jpype 相关的运行时错误
- google-kubernetes-engine - 使用 ingress 时了解 GKE 上后端服务的运行状况检查
- c - 1252-142 来自 AIX 汇编器的语法错误,由于本地标签
- ios - Swift - 想要在单击集合视图单元格内的按钮时进行更改
- google-chrome-extension - 在 Google Chrome 扩展程序中,如何使用 page_action 执行一些清理?
- iot-devkit - VS Code 无法自动识别 AZ-3166 开发套件
- python-3.x - Smart Beta 投资组合:如何根据每个日期的美元交易量生成权重
- python-3.x - 如何用 pyintaller 解决 RecursionError?
- php - 数组到字符串转换 laravel 5.6