【问题标题】:JSON Schema: How to check if a field contains a valueJSON Schema:如何检查字段是否包含值
【发布时间】:2018-12-03 20:17:22
【问题描述】:

我有一个 JSON 模式验证器,我需要在其中检查特定字段 email 以查看它是否是 4 封可能的电子邮件之一。让我们将可能性称为['test1', 'test2', 'test3', 'test4']。有时电子邮件包含\n 换行符,所以我也需要考虑这一点。是否可以在 JSON Schema 中执行字符串包含方法?

这是我没有电子邮件检查的架构:

{
  "type": "object",
  "properties": {
    "data": {
        "type":"object",
        "properties": {
            "email": {
                "type": "string"
            }
        },
    "required": ["email"]
    }
  }
}

我的输入载荷是:

{
  "data": {
      "email": "test3\njunktext"
      }
}

我需要以下有效负载来通过验证,因为其中包含 test3。谢谢!

【问题讨论】:

    标签: python json jsonschema


    【解决方案1】:

    我可以想到两种方法:

    使用enum,您可以定义有效电子邮件列表:

    {
      "type": "object",
      "properties": {
        "data": {
          "type": "object",
          "properties": {
            "email": {
              "enum": [
                "test1",
                "test2",
                "test3"
              ]
            }
          },
          "required": [
            "email"
          ]
        }
      }
    }
    

    或者使用pattern,它允许您使用正则表达式来匹配有效的电子邮件:

    {
      "type": "object",
      "properties": {
        "data": {
          "type": "object",
          "properties": {
            "email": {
              "pattern": "test"
            }
          },
          "required": [
            "email"
          ]
        }
      }
    }
    

    【讨论】:

    • enum 方法不起作用,因为它会排除值中的其他文本。你必须使用pattern
    • 感谢您的反馈。除非我弄错了,否则我已经在回答中考虑了这种情况。 enum 方法也很值得了解,并在 OP 只需要检查静态电子邮件列表的情况下被提及。
    • 谢谢!模式对我有用,对于多种模式,我使用了 anyOf: [ {type: string, pattern: pattern},... etc]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多