Alternatives to JavaScript eval() for parsing JSON

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


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.


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

See this answer: Safe json parsing with jquery?