为什么 json 架构与 json 不匹配?

Why jsonschema is not match with the json?

鉴于此,我有以下 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字符串中的转义符,所以现在json无效了。 您还可以在验证 json 时看到,例如 jsonlint.com

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

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

完整示例:(不要忘记 select draft-04 on https://jsonschemalint.com/,或将架构更改为 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,}$"
    }
  }
}