如何使用 JSON Schema 将字符串值验证为 json 文本中的数字?

Jak*_*134 2 c# jsonschema json-schema-validator

我希望能够将答案字段验证为数值。下面的代码片段是一个答案,是更大的答案词典的一部分。每个答案都遵循通用格式,因此答案字段需要为字符串类型。

            "1": {
                "answer": "80035",
                "web_validated": true,
                "web_error_string": "",
                "server_error_string": ""
            },
Run Code Online (Sandbox Code Playgroud)

当我们使用 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
      }
Run Code Online (Sandbox Code Playgroud)

我们当前用于验证问题 ID 的 JSON 架构:1。

"definitions": {
    "question1-1": {
      "type": "object",
      "properties": {
        "answer": {
          "type": "string",
          "minLength": 1
        }
      }
      //other definitions removed
  } 
}
Run Code Online (Sandbox Code Playgroud)

以上是此问题中显示的答案的 JSON 架构定义。

可能的解决方案:

  1. 将答案字段转换为数字字段,即去掉“” - 这确实有效,但成本更高,而且是一种黑客行为。因此,在验证之前进行预处理。
  2. 只需将答案字段验证为字符串,即不为空、不为空和最小长度检查。

我更想看看 JSON Schema 是否可以实现这一点?

小智 10

正如其他人提到的,您可以使用模式。以下是添加到示例中的语法:

"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
  } 
}
Run Code Online (Sandbox Code Playgroud)