JSON.parse vs. eval()

JavascriptJson

Javascript Problem Overview


My Spider Sense warns me that using eval() to parse incoming JSON is a bad idea. I'm just wondering if JSON.parse() - which I assume is a part of JavaScript and not a browser-specific function - is more secure.

Javascript Solutions


Solution 1 - Javascript

You are more vulnerable to attacks if using eval: JSON is a subset of Javascript and json.parse just parses JSON whereas eval would leave the door open to all JS expressions.

Solution 2 - Javascript

All JSON.parse implementations most likely use eval()

JSON.parse is based on Douglas Crockford's solution, which uses eval() right there on line 497.

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

j = eval('(' + text + ')');

The advantage of JSON.parse is that it verifies the argument is correct JSON syntax.

Solution 3 - Javascript

Not all browsers have native JSON support so there will be times where you need to use eval() to the JSON string. Use JSON parser from http://json.org as that handles everything a lot easier for you.

Eval() is an evil but against some browsers its a necessary evil but where you can avoid it, do so!!!!!

Solution 4 - Javascript

There is a difference between what JSON.parse() and eval() will accept. Try eval on this:

var x = "{"shoppingCartName":"shopping_cart:2000"}"

eval(x)         //won't work
JSON.parse(x)   //does work

See this example.

Solution 5 - Javascript

If you parse the JSON with eval, you're allowing the string being parsed to contain absolutely anything, so instead of just being a set of data, you could find yourself executing function calls, or whatever.

Also, JSON's parse accepts an aditional parameter, reviver, that lets you specify how to deal with certain values, such as datetimes (more info and example in the inline documentation here)

Solution 6 - Javascript

JSON is just a subset of JavaScript. But eval evaluates the full JavaScript language and not just the subset that’s JSON.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKevin MajorView Question on Stackoverflow
Solution 1 - JavascriptjldupontView Answer on Stackoverflow
Solution 2 - JavascriptplodderView Answer on Stackoverflow
Solution 3 - JavascriptAutomatedTesterView Answer on Stackoverflow
Solution 4 - JavascriptJeff LoweryView Answer on Stackoverflow
Solution 5 - JavascriptDavid HedlundView Answer on Stackoverflow
Solution 6 - JavascriptGumboView Answer on Stackoverflow