JSON (schema) validation with escaped characters i

2019-04-28 09:23发布

问题:

The following JSON object is valid:

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

Whereas this one is not:

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

It's the escaped dot (\.), but I can't see why this should not be valid JSON. I need to include such patterns in my real JSON schemas. The regexp there are far more complex and there is no way missing out on excaping, especially the dot.

BTW, escaping hypens in character classes such as in [a-z\-] breaks validation as well.

How do I fix that?

Edit: I used http://jsonlint.com/, http://jsonvalidator.mytechlabs.com/ and a couple of node libraries.

回答1:

You need to double escape here. The slash is an escape character in json so you can't escape the dot (as it sees it) instead you need to escape that backslash so your regex comes out with \. like it should (json is expecting a reserved character after the escape ie a quote or another slash or something).

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