在模式中使用转义字符的JSON(模式)验证失败



以下JSON对象有效:

{
    "foo": "bar",
    "pattern": "^(/?[-a-zA-Z0-9_.]+)+$"
}

而这个是而不是:

{
    "foo": "bar",
    "pattern": "^(/?[-a-zA-Z0-9_.]+)+.jpg$"
}

这是转义的 (.),但我不明白为什么这不应该是有效的JSON。我需要在实际的JSON模式中包含这样的模式。那里的regexp要复杂得多,而且不可能错过转义,尤其是点。

顺便说一句,在字符类中转义连字符也会破坏验证,例如在[a-z-]中。

我如何解决这个问题?

编辑:我使用http://jsonlint.com和几个节点库。

这里需要双转义。斜杠是json中的转义字符,所以你不能转义点(因为它看到它),相反,你需要转义反斜杠,所以你的正则表达式出来与.像它应该(json期待转义后的保留字符即引号或另一个斜杠或其他东西)。

// passes validation
{
    "foo": "bar",
    "pattern": "^(/?[-a-zA-Z0-9_.]+)+\.jpg$"
}

你可以从ajv-keywords中使用regexp

import Ajv from 'ajv';
import AjvKeywords from 'ajv-keywords';
// ajv-errors needed for errorMessage
import AjvErrors from 'ajv-errors';
const ajv = new Ajv.default({ allErrors: true });
AjvKeywords(ajv, "regexp");
AjvErrors(ajv);
// modification of regex by requiring Z https://www.regextester.com/97766
const ISO8601UTCRegex = /^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?Z$/;
const typeISO8601UTC = {
  "type": "string",
  "regexp": ISO8601UTCRegex.toString(),
  "errorMessage": "must be string of format 1970-01-01T00:00:00Z. Got ${0}",
};
const schema = {
  type: "object",
  properties: {
    foo: { type: "number", minimum: 0 },
    timestamp: typeISO8601UTC,
  },
  required: ["foo", "timestamp"],
  additionalProperties: false,
};
const validate = ajv.compile(schema);
const data = { foo: 1, timestamp: "2020-01-11T20:28:00" }
if (validate(data)) {
  console.log(JSON.stringify(data, null, 2));
} else {
  console.log(JSON.stringify(validate.errors, null, 2));
}
https://github.com/rofrol/ajv-regexp-errormessage-example

最新更新