JSON (schema) validation with escaped characters in patterns fails

时光毁灭记忆、已成空白 提交于 2019-12-22 04:29:07

问题


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


来源:https://stackoverflow.com/questions/30739738/json-schema-validation-with-escaped-characters-in-patterns-fails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!