JSON.parse vs. eval ()

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 part of JavaScript, and not a browser-specific function, is more secure.

+86
json javascript
Dec 03 '09 at 22:14
source share
6 answers

If you use eval , you are more vulnerable to attacks : JSON is a subset of Javascript, and json.parse just parses JSON, while eval will leave the door open for all JS expressions.

+102
Dec 03 '09 at 22:20
source share

All JSON.parse implementations most likely use eval()

JSON.parse based on a Douglas Crockford solution that uses eval() directly 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 checks that the argument is the correct JSON syntax.

+32
Apr 20 '10 at
source share

Not all browsers have built-in JSON support, so there will be times when you need to use eval() for a JSON string. Use the JSON parser from http://json.org as everything is much simpler for you.

eval() is evil, but against some browsers it is a necessary evil, but where you can avoid it, do it !!!!!

+13
Dec 03 '09 at 22:22
source share

If you parse JSON with eval , you allow the parsing of the string to contain anything, so instead of just being a dataset, you could make function calls or something else.

In addition, JSON parse accepts an optional reviver parameter, which allows you to specify how to handle certain values, such as dates (more information and an example in the built-in documentation here )

+9
Dec 03 '09 at 22:20
source share

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

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

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

See this example .

+9
Feb 22 '14 at 3:09
source share

JSON is just a subset of JavaScript. But eval appreciates the full JavaScript language, not just a subset of JSON.

+4
Dec 03 '09 at 22:16
source share



All Articles