Alternatives to JavaScript eval() for pars

2019-01-08 18:43发布

Quick Question. Eval in JavaScript is unsafe is it not? I have a JSON object as a string and I need to turn it into an actual object so I can obtain the data:

function PopulateSeriesFields(result) 
{
    data = eval('(' + result + ')');
    var myFakeExample = data.exampleType
}

If it helps I am using the $.ajax method from jQuery.

Thanks

9条回答
孤傲高冷的网名
2楼-- · 2019-01-08 19:40

You should use JSON and write JSON.parse.

"Manual" parsing is too slow, so JSON.parse implementation from the library checks stuff and then ends up using eval, so it is still unsafe. But, if you are using a newer browser (IE8 or Firefox), the library code is not actually executed. Instead, native browser support kicks in, and then you are safe.

Read more here and here.

查看更多
The star\"
3楼-- · 2019-01-08 19:46

The alternative to evaluating the code is to parse it manually. It's not as hard as it sounds but it's quite a lot heavier at runtime. You can read about it here.

The important part to note is evaluating JSON is not inherently insecure. As long as you trust the source not to balls things up. That includes making sure that things passed into the JSON encoder are properly escaped (to stop people 2 steps up the stream executing code on your users' machines).

查看更多
我想做一个坏孩纸
4楼-- · 2019-01-08 19:49

Unsafe? That depends on if you can trust the data.

If you can trust that the string will be JSON (and won't include, for example, functions) then it is safe.

That said - if you are using jQuery, why are you doing this manually? Use the dataType option to specify that it is JSON and let the library take care of it for you.

查看更多
登录 后发表回答