首页 > 解决方案 > 如何使用 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 模式定义。

可能的解决方案:

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

我更愿意看看 JSON Schema 是否可行?

标签: c#jsonschemajson-schema-validator

解决方案


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

"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
  } 
}

推荐阅读