Why is eval in JS bracketed to handle JSON data

  • 2020-05-27 04:15:38
  • OfStack

Thanks to the rise of Ajax, the lightweight data format JSON has become increasingly popular as a transport format between the client and the server, and the problem is how to convert the JSON data built on the server into available JavaScript objects. Using the eval function is undoubtedly a simple and straightforward method. To convert the JSON string, wrap 1 layer of parentheses around it:


var jsonObject = eval("(" + jsonFormat + ")");

Why put parentheses?

The purpose of the parentheses is to force the eval function to process the JavaScript code by forcing the expression inside the parentheses (expression) to be executed as an object, rather than as a statement (statement). For example, if the object literal {} is not enclosed, eval will recognize the curly braces as the start and end of the JavaScript code block, and {} will be considered to have executed an empty statement. So the following two results are different:


alert(eval("{}");  // return undefined
alert(eval("({})");// return object[Object]

That's all for this article, I hope you enjoy it.


Related articles: