Home >Web Front-end >JS Tutorial >Why does eval in JS need to add brackets when processing JSON data_javascript skills

Why does eval in JS need to add brackets when processing JSON data_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:04:291115browse

Due to the rise of Ajax, JSON, a lightweight data format, has gradually become popular as a transmission format between the client and the server. The question that arises is how to convert JSON data built on the server side into usable form. JavaScript object. Using the eval function is undoubtedly a simple and direct method. When converting, you need to wrap the JSON string with a layer of parentheses:

Copy code The code is as follows:

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

Why add brackets?

The purpose of adding parentheses is to force the eval function to convert the expression in the parentheses into an object instead of executing it as a statement when processing JavaScript code. For example, take the object literal {}. If no outer brackets are added, then eval will recognize the braces as the beginning and end marks of the JavaScript code block, and {} will be considered to execute an empty statement. So the following two execution results are different:

Copy code The code is as follows:

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

The above is the entire content of this article, I hope you all like it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn