What is the difference between JSON.parse() and eval() methods for accessing JSON object in JavaScript?

Answered

What is the difference between JSON.parse() and eval() methods for accessing JSON object in JavaScript?

Ninja Asked on 19th September 2018 in JSON.
Add Comment
1 Answer(s)
Best answer

JSON is derived from JavaScript and its syntax is mostly a subset of the language, it is often possible to use the JavaScript eval() function to parse JSON data. The eval() function can compile and execute any JavaScript program represented in the form of a string. This is considered unsafe because of potential security issues. Instead, a JSON parser library or JavaScript’s native JSON support like JSON.parse() should be used for reading and writing JSON. A correctly implemented JSON parser will only accept valid JSON, preventing potentially malicious code from being inadvertently executed. Performance wise also eval() is also generally slower than the JSON.parse() method.

As mentioned above, eval will execute any valid JavaScript code. Thus the following would cause an alert:
var text = “alert(‘Test eval and parse’)”;
var obj = eval(text);

JSON.parse, however, will only return successfully if the string passed in is valid JSON:
// gives “SyntaxError: JSON.parse”
var txt = JSON.parse(text);

Ninja Answered on 19th September 2018.
Add Comment