Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON (schema) validation with escaped characters in patterns fails

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 and a couple of node libraries.

like image 543
aaki Avatar asked Jun 09 '15 18:06

aaki


1 Answers

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$"
}
like image 173
evanmcdonnal Avatar answered Oct 18 '22 10:10

evanmcdonnal