正则表达式以验证JSON [英] Regex to validate JSON
问题描述
我正在寻找允许我验证json的正则表达式.
I am looking for a Regex that allows me to validate json.
我对Regex来说是个新手,我知道使用Regex进行解析很不好,但是可以用来验证吗?
I am very new to Regex's and i know enough that parsing with Regex is bad but can it be used to validate?
推荐答案
是的,可以进行完整的正则表达式验证.
大多数现代正则表达式实现都允许递归正则表达式,该正则表达式可以验证完整的JSON序列化结构. json.org规范使其非常简单.
$pcre_regex = '
/
(?(DEFINE)
(?<number> -? (?= [1-9]|0(?!\d) ) \d+ (\.\d+)? ([eE] [+-]? \d+)? )
(?<boolean> true | false | null )
(?<string> " ([^"\\\\]* | \\\\ ["\\\\bfnrt\/] | \\\\ u [0-9a-f]{4} )* " )
(?<array> \[ (?: (?&json) (?: , (?&json) )* )? \s* \] )
(?<pair> \s* (?&string) \s* : (?&json) )
(?<object> \{ (?: (?&pair) (?: , (?&pair) )* )? \s* \} )
(?<json> \s* (?: (?&number) | (?&boolean) | (?&string) | (?&array) | (?&object) ) \s* )
)
\A (?&json) \Z
/six
';
它与 PCRE函数一起在PHP中运行良好.应该在Perl中保持不变;并且可以肯定地适用于其他语言.此外,它还可以使用 JSON测试用例.
It works quite well in PHP with the PCRE functions . Should work unmodified in Perl; and can certainly be adapted for other languages. Also it succeeds with the JSON test cases.
一种更简单的方法是按照 RFC4627第6 节中的规定进行最小一致性检查.但是,它仅用作安全性测试和基本的非有效性预防措施:
A simpler approach is the minimal consistency check as specified in RFC4627, section 6. It's however just intended as security test and basic non-validity precaution:
var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
eval('(' + text + ')');
这篇关于正则表达式以验证JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!