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:
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
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).
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.
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.
you can try it like this
var object = new Function("return " + jsonString)()
If you are using jQuery, as of version 1.4.1 you can use jQuery.parseJSON()
See this answer: Safe json parsing with jquery?