這裏的official JavaScript parser做什麼:
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
...
的除外內置JSON parsing support是在現代瀏覽器,這是所有(基於庫的)安全JSON解析器做(即正則表達式在eval
之前測試)。
安全庫(除官方json2實現)
原型的isJSON
功能。
Mootools'JSON.decode
函數(同樣,通過regex test before eval
)。
不安全庫:
道場的fromJson
不不提供安全eval
ING。 Here is their entire implementation (minus comments):
dojo.fromJson = function(json) {
return eval("(" + json + ")");
}
jQuery的不提供安全的JSON eval
「荷蘭國際集團,但看到官方插件的secureEvalJSON
功能(線143)。
這是一個正則表達式的問題 – Hugoware 2009-07-17 14:03:12