【问题标题】:How to validate a string value as a number in json text using JSON Schema?如何使用 JSON Schema 将字符串值验证为 json 文本中的数字?
【发布时间】:2019-01-24 12:03:16
【问题描述】:

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

            "1": {
                "answer": "80035",
                "web_validated": true,
                "web_error_string": "",
                "server_error_string": ""
            },

这会产生一个问题,因为我们使用 JSON Schema 来验证答案字典。我们需要将答案字段验证为数值,这是由字典必须遵守的 JSON 模板确定的。以下是字典中一个问题的上述答案的模板的 sn-p。

      {
        "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. 只需将答案字段验证为 字符串,i.y 不为空,不为空和最小长度检查。

我想看看 JSON Schema 是否可行?

【问题讨论】:

  • 嗯,总是有pattern 来指定一个匹配“数字”的正则表达式(可能像[0-9]+ 一样简单,但如果你愿意,你可以变得更花哨)。就个人而言,我更喜欢将这样的“语义”验证推迟到处理层,仅仅是因为它提供了更大的灵活性。在这种情况下,通用验证器很少提供信息丰富的错误消息,并且短路常规处理可能会剥夺您记录额外详细信息的机会(并改变您对什么是有效的想法)。
  • 是的,上面的评论是正确的,唯一的方法是使用描述的正则表达式。如果您有任何其他问题,请随时通过网站上的讨论链接加入 JSON Schema slack =]

标签: c# jsonschema json-schema-validator


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-29
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    相关资源
    最近更新 更多