Home > Web Front-end > JS Tutorial > body text

JSON and JavaScript eval usage instructions_json

WBOY
Release: 2016-05-16 18:25:06
Original
1093 people have browsed it

The JSON format can be object, array, value, string, or number.

Copy code The code is as follows:



Reference: http://www.json.org/json-zh.html



Let’s take a look at JavaScript’s eval function.
The eval function evaluates a given string of JavaScript code and attempts to execute the expression or a series of legal JavaScript statements contained in the string. The eval function will return the value or reference contained in the last expression or statement.

Code
Copy code The code is as follows:



The difference between JSON and object literals: The name part of JSON is strictly represented by quoted names.
Code
Copy code The code is as follows:



Due to the rise of Ajax, JSON, a lightweight data format, has gradually become popular as a format for transmission between the client and the server. The problem that arises is how to convert the JSON data built on the server side. For available JavaScript objects, using the eval function is undoubtedly a simple and straightforward method. When converting, you need to wrap the JSON string with a layer of garden brackets:

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

The purpose of adding garden brackets is to force eval The function forces the expression within the parentheses to be converted to an object when evaluating JavaScript code, rather than being executed as a statement. For example, if the object literal {} is not enclosed in outer brackets, eval will distinguish the braces as the beginning and end markers 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]

Why do we need to add quotes to the name part in JSON format? Because the eval function will interpret {foo:"bar"} as a legal JavaScript statement, not an expression. But people often want eval to interpret this code as an object. So the JSON format forces you to put quotes around the name, and combined with parentheses, eval will not incorrectly interpret JSON as a code block.
 
Copy code The code is as follows:

//eval error parsing semantics
alert(eval('{foo:"bar"}')); //return "bar",incorrect
//eval correctly parses JSON
alert(eval('({"foo":"bar" })'));//return JSON object,correct

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template