快速问题.JavaScript中的Eval是不安全的,不是吗?我有一个JSON对象作为字符串,我需要把它变成一个实际的对象,所以我可以获取数据:
function PopulateSeriesFields(result)
{
data = eval('(' + result + ')');
var myFakeExample = data.exampleType
}
Run Code Online (Sandbox Code Playgroud)
如果它有助于我使用jQuery中的$ .ajax方法.
谢谢
可能重复:
jQuery使用(new Function("return"+ data))(); 而不是eval(数据); 解析JSON,为什么?
给定一个表示有效JSON字符串的字符串,这两种解析方法之间是否存在差异:
var str, obj;
str = '{"prop":"value"}';
// method 1:
obj = eval( '(' + str + ')' );
// method 2:
obj = ( new Function( 'return (' + str + ');' ) )();
Run Code Online (Sandbox Code Playgroud)
我注意到jQuery使用第二种方法来解析JSON字符串(在没有内置JSON解析器的环境中).我想知道他们为什么不使用第一种方法.为什么要创建一个函数对象并在可以使用时调用它eval()?
我注意到jQuery parseJSON基本上做了一个简单的正则表达式"检查":
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
.replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {
// Try to use the native JSON parser first
return window.JSON && window.JSON.parse ?
window.JSON.parse( data ) :
(new Function("return …Run Code Online (Sandbox Code Playgroud)