Alternatives to JavaScript eval() for parsing JSON

Deadly 提交于 2019-11-27 07:39:42

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

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.

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.

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.

thomh

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

See this answer: Safe json parsing with jquery?

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.

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).

you can try it like this

var object = new Function("return " + jsonString)()

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"}');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!