parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }
主要的难点:json
if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); }
检测逻辑借助于 json2.js , 如下正则在头部定义了 用于匹配转义字符 rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g 用于匹配有效字符值 'str' true false null Number rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g 用于匹配正确的左方括号 rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g 用于检测字符串中知否只含有执行字符 ] , : { } rvalidchars = /^[\],:{}\s]*$/ 检测传入的字符串是一个 切实 的 JSON 数据 先把转义字符替换成@, 再把有效字符替换为"]", 在删除正确的左方括号, 最后检测剩下的字符串是否指包含指定的几个字符。 特别说明: 此处注释出自 @高云 的书中原文【小编能力有限,解释不清这些正则的意思】
JSON2.JS的源码解读:http://www.javashuo.com/article/p-dpxkuarl-hs.html