Difference between eval and window.json.parse for a dealing with a responseText?
I have the following code at hand
var finalCompleteData = eval("("+jsonresponse.responseText+")");
When I used this, I received a security flaw error in Fortify saying that it might lead to Javascript Hacking. So, I changed it to
var finalCompleteData = window.json.parse(jsonresponse.r开发者_运维问答esponseText);
For this, Fortify did not show the error. What the window.json.parse method do ?
Can you please explain. Thanks in advance :-)
eval
will execute any JavaScript code which it is supposed to evaluate, and it evaluates with the highest level of security. This means that if your response text returns non-json code, but valid javascript, the eval
will execute it. The sky is the limit with this, it can add new functions, change variables, redirect the page.
With window.json.parse
only json will be evaluated, so the risk of rogue code getting entered is much much less.
eval is able to run any kind of javascript code - not just simple objects/arrays as JSON.parse would (it examines the contents - validating json). For this reason eval should be avoided in places where you cannot guarantee the input.
As others have mentioned, eval
will execute any valid JavaScript code. Thus the following would cause an alert:
var jsObject = eval("alert('blah')");
You're essentially trusting any input from a given source, which is not safe in general. A malicious user could take advantage of the eval and execute harmful JavaScript.
JSON.parse
, however, will only return successfully if the string passed in is valid JSON:
// gives "SyntaxError: JSON.parse"
var jsObject = JSON.parse("alert('blah')");
Thus it's not executing just anything it's given the way eval
is.
精彩评论