【问题标题】:Why jsonschema is not match with the json?为什么jsonschema与json不匹配?
【发布时间】:2020-07-19 10:34:03
【问题描述】:

鉴于此,我有以下 json:

{
"msg":"aaaa",
"email":"aaa@gmail.com"
}

然后,我写了下面的 json 架构:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Json schema sample",
  "type": "object",
  "additionalProperties": true,
  "required": [
    "msg",
    "email"
  ],

  "properties": {
    "msg": {
      "type": "string"
    },
    "email": {
      "type": "string",
      "pattern": "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$"
    }
  }
}

遗憾的是它与 json 不匹配。

如果您删除,"pattern": "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$",它是用于检查email 的正则表达式,那么它工作得很好。 Please test it in this website.

我确信我的电子邮件正则表达式没问题。但我不知道为什么它在 json 架构中不起作用!

【问题讨论】:

    标签: json jsonschema json-schema-validator


    【解决方案1】:

    \ 也是 json 字符串中的转义字符,所以现在是无效的 json。 您还可以在验证 json 时看到这一点,例如在 jsonlint.com

    所以你的模式需要第二个\

    pattern": "^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}$"
    

    完整示例:(不要忘记在https://jsonschemalint.com/ 上选择draft-04,或者将架构更改为draft-07)

    {
      "$schema": "http://json-schema.org/draft-04/schema#",
      "title": "Json schema sample",
      "type": "object",
      "additionalProperties": true,
      "required": [
        "msg",
        "email"
      ],
      "properties": {
        "msg": {
          "type": "string"
        },
        "email": {
          "type": "string",
          "pattern": "^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}$"
        }
      }
    }
    

    【讨论】:

    • 不应该正则表达式 . 仍然匹配字符串中的文字 . 吗?
    • @Ether 是的,但这里不是这样。这里单个 `` 导致无效的 json 模式。我已经编辑了我的答案以使其更清楚。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 2011-09-12
    相关资源
    最近更新 更多