JSON (schema) validation with escaped characters in templates fails

Let's assume the following JSON object:

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

      

While this one does not :

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

      

It's a cursory period ( \.

), but I don't understand why it shouldn't be valid JSON. I need to include templates like this in my real JSON schemas. The regex is much more complex and there is no way to miss the extraction, especially the point.

By the way, escaping hems in character classes such as in [a-z\-]

also validates.

How to fix it?

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

+3


source to share


1 answer


You need to double your getaway here. Slash is an escape character in json, so you cannot escape the period (as it sees it), instead you need to escape that backslash so that your regex will get \.

as it should (json expects a reserved character after escape, i.e. (i.e. quote or other forward slash or whatever).



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

      

+3


source







All Articles