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