1

I'm using a regex to validate a property, in json schema.

The schema is as follows:

{
    "$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"
            ]
        }
    }
}

Where the big regex is for a semver - c.f. here.

Using jsonlint I get:

Error: Parse error on line 14:
...le.",            "pattern": "^(0|[1-9]\d*)\.(0|[
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'

Surely I don't have to escape regex patterns in json schema? Strings should be treated as literals, right? Does anyone know what on earth is going on here?

1 Answer 1

2

You can't use certain characters without escaping, even in literal strings: https://www.freeformatter.com/json-escape.html

Your regex needs to have all backslashes escaped (you can do this using the tool at the link).

Sign up to request clarification or add additional context in comments.

2 Comments

ermahgodd. Because the regexes aren't crazy enough already. Useful escaping tool, though. Thank you Oli!
This is a requirement of JSON and indeed Javascript strings, not anything specific to JSON Schema. If you were using Javascript to create your schemas, you could use the toString method on a regular expression: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.