为什么正则表达式模式会导致 jsonschema 中出现 "bad string" 错误?
Why do regex patterns result in "bad string" errors in jsonschema?
我正在使用正则表达式在 json 模式中验证 属性。
架构如下:
{
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "http://example.com/example.json",
"type": "object",
"required": [
"library_version"
],
"properties": {
"library_version": {
"$id": "#/properties/library_version",
"type": "string",
"title": "Library version",
"description": "The library version (e.g. 0.0.1) used to create this file.",
"pattern": "^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$",
"message": {
"required": "Library version is a required property",
"pattern": "The version must be a semantic form, like 0.0.1 (see https://semver.org/)"
},
"examples": [
"0.0.1"
]
}
}
}
大正则表达式用于 semver - c.f. here.
使用 jsonlint 我得到:
Error: Parse error on line 14:
...le.", "pattern": "^(0|[1-9]\d*)\.(0|[
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
我真的不必在 json 模式中转义正则表达式模式吗?字符串应该被视为文字,对吧?有谁知道这到底是怎么回事?
您不能在不转义的情况下使用某些字符,即使在文字字符串中也是如此:https://www.freeformatter.com/json-escape.html
您的正则表达式需要转义所有反斜杠(您可以使用 link 中的工具执行此操作)。
我正在使用正则表达式在 json 模式中验证 属性。
架构如下:
{
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "http://example.com/example.json",
"type": "object",
"required": [
"library_version"
],
"properties": {
"library_version": {
"$id": "#/properties/library_version",
"type": "string",
"title": "Library version",
"description": "The library version (e.g. 0.0.1) used to create this file.",
"pattern": "^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$",
"message": {
"required": "Library version is a required property",
"pattern": "The version must be a semantic form, like 0.0.1 (see https://semver.org/)"
},
"examples": [
"0.0.1"
]
}
}
}
大正则表达式用于 semver - c.f. here.
使用 jsonlint 我得到:
Error: Parse error on line 14:
...le.", "pattern": "^(0|[1-9]\d*)\.(0|[
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
我真的不必在 json 模式中转义正则表达式模式吗?字符串应该被视为文字,对吧?有谁知道这到底是怎么回事?
您不能在不转义的情况下使用某些字符,即使在文字字符串中也是如此:https://www.freeformatter.com/json-escape.html
您的正则表达式需要转义所有反斜杠(您可以使用 link 中的工具执行此操作)。