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条回答
Anthone
2楼-- · 2019-01-08 19:23

Well, safe or not, when you are using jQuery, you're better to use the $.getJSON() method, not $.ajax():

$.getJSON(url, function(data){
    alert(data.exampleType);
});

eval() is usually considered safe for JSON parsing when you are only communicating with your own server and especially when you use a good JSON library on server side that guarantees that generated JSON will not contain anything nasty.

Even Douglas Crockford, the author of JSON, said that you shouldn't use eval() anywhere in your code, except for parsing JSON. See the corresponding section in his book JavaScript: The Good Parts

查看更多
SAY GOODBYE
3楼-- · 2019-01-08 19:24

If you are using jQuery, as of version 1.4.1 you can use jQuery.parseJSON()

See this answer: Safe json parsing with jquery?

查看更多
劳资没心,怎么记你
4楼-- · 2019-01-08 19:25

Another great alternative is YUI: http://yuilibrary.com/yui/docs/json/

So your code would be something like:

Y.JSON.parse('{"id": 15, "name": "something"}');
查看更多
别忘想泡老子
5楼-- · 2019-01-08 19:29

Using JavaScript’s eval is unsafe. Because JSON is just a subset of JavaScript but JavaScript’s eval allows any valid JavaScript.

Use a real JSON parser like the JSON parser from json.org instead.

查看更多
祖国的老花朵
6楼-- · 2019-01-08 19:29

you can try it like this

var object = new Function("return " + jsonString)()
查看更多
不美不萌又怎样
7楼-- · 2019-01-08 19:38

If you can't trust the source, then you're correct...eval is unsafe. It could be used to inject code into your pages.

Check out this link for a safer alternative:

JSON in Javascript

The page explains why eval is unsafe and provides a link to a JSON parser at the bottom of the page.

查看更多
登录 后发表回答