【问题标题】:Why do regex patterns result in "bad string" errors in jsonschema?为什么正则表达式模式会导致 jsonschema 中出现“错误字符串”错误?
【发布时间】:2020-11-30 21:29:36
【问题描述】:

我正在使用正则表达式来验证 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 模式中转义正则表达式模式?字符串应该被视为文字,对吧?有谁知道这里到底发生了什么?

【问题讨论】:

    标签: json regex schema jsonschema


    【解决方案1】:

    你不能在不转义的情况下使用某些字符,即使是在文字字符串中:https://www.freeformatter.com/json-escape.html

    您的正则表达式需要对所有反斜杠进行转义(您可以使用链接中的工具执行此操作)。

    【讨论】:

    • ermahgodd。因为正则表达式还不够疯狂。不过,有用的转义工具。谢谢奥利!
    • 这是 JSON 和 Javascript 字符串的要求,而不是 JSON Schema 特有的任何内容。如果您使用 Javascript 创建架构,则可以在正则表达式上使用 toString 方法:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    猜你喜欢
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 2013-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多