使用parseJSON代替eval

有些程序员如果没有很好的在javascript中解析json数据,往往会直接eval把json转成js对象,这时候如果json的数据中包含了被注入的恶意数据,则可能导致代码注入的问题。

正确的做法是分割出json里包含的特殊字符,然后再解析为对象
 

 1 parseJSON: function( data ) {
 2   if ( typeof data !== "string" || !data ) {
 3    return null;
 4   }
 5 
 6   // Make sure leading/trailing whitespace is removed (IE can't handle it)
 7   data = jQuery.trim( data );
 8   
 9   // Make sure the incoming data is actual JSON
10   // Logic borrowed from http://json.org/json2.js
11   if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
12    .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
13    .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {
14 
15    // Try to use the native JSON parser first
16    return window.JSON && window.JSON.parse ?
17     window.JSON.parse( data ) :
18     (new Function("return " + data))();
19 
20   } else {
21    jQuery.error( "Invalid JSON: " + data );
22   }
23  }

 

所以,以后请使用parseJSON代替eval。

你可能感兴趣的:(使用parseJSON代替eval)