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():
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 PartsIf you are using jQuery, as of version 1.4.1 you can use jQuery.parseJSON()
See this answer: Safe json parsing with jquery?
Another great alternative is YUI: http://yuilibrary.com/yui/docs/json/
So your code would be something like:
Using JavaScript’s
eval
is unsafe. Because JSON is just a subset of JavaScript but JavaScript’seval
allows any valid JavaScript.Use a real JSON parser like the JSON parser from json.org instead.
you can try it like this
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.