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

Parsing JSON strings with eval in javascript_Basic knowledge

WBOY
Release: 2016-05-16 15:13:17
Original
1188 people have browsed it

We all know that advanced browsers can use the JSON.parse() API to parse a JSON string into JSON data. For a slightly less appropriate approach, we can use the eval() function.

var str = '{"name": "hanzichi", "age": 10}';
var obj = eval('(' + str + ')');
console.log(obj); // Object {name: "hanzichi", age: 10}
Copy after login

Have you noticed that when passing parameters to eval(), the str variable is wrapped in parentheses? Why do this?

Let’s first look at the definition and use of the eval function.

The parameter of eval() is a string. If the string represents an expression, eval() evaluates the expression. If the argument represents one or more JavaScript declarations, then eval() executes the declarations. Do not call eval() to evaluate arithmetic expressions; JavaScript automatically evaluates arithmetic expressions.

To put it simply, the parameter of the eval function is a string. If the string is "noString", the result will be a normal JavaScript statement that can be run.

How to say? For example, the following code:

var str = "alert('hello world')";
eval(str);
Copy after login

“hello world” pops up after execution. We turn the str variable into "noString". A rough approach is to remove the outer quotes and make internal adjustments (escaping, etc.), and then it becomes:

alert('hello world')
Copy after login

very good! This is a normal JavaScript statement that works! Run it!

Going back to the original question, why do JSON strings need to be wrapped in parentheses? If you don’t add it, it will look like this:

var str = '{"name": "hanzichi", "age": 10}';
var obj = eval(str); // Uncaught SyntaxError: Unexpected token :
Copy after login

Well, an error was reported. Why is an error reported? Try converting str to “noString” and execute:

{"name": "hanzichi", "age": 10}; 
// Uncaught SyntaxError: Unexpected token :
Copy after login

There is no doubt that a JSON object or an object is not an executable JavaScript statement at all! Wait, try the following code:

var str = '{name: "hanzichi"}';
var obj = eval(str);
console.log(obj); // hanzichi
Copy after login

What the hell is this? But adding "" to name returns an error?

var str = '{"name": "hanzichi"}';
var obj = eval(str); // Uncaught SyntaxError: Unexpected token :
console.log(obj);
Copy after login

Okay, I’m almost dizzy. In fact, you can still “nostring” str to see if it is a JavaScript statement that can be executed correctly. The result of the former is:

{name: "hanzichi"}
Copy after login

This is indeed a legal JavaScript statement. {} We can use it not only in scenarios such as if and for statements, but also at any time, because before ES6 JavaScript only had block-level scope, so there would be no conflict with scope. After removing {}, name: "hanzichi" is also a legal statement. It is a label statement. The label statement is very useful for jumping out of nested loops. For details, please refer to label. As a mark of the label statement, name cannot be quoted. Tags can be placed anywhere in JavaScript code, even if they are not used.

Once an object has two keys, such as {name: "hanzichi", age: 10}, ok, two label statements? Treat "hanzhichi" and 10 as statements respectively, but statements can only be connected with seal numbers! (Only commas can be used between expressions). So it’s okay to change it to the following:

var str = '{name: "hanzichi"; age: 10}';
var obj = eval(str); 
console.log(obj); // 10
Copy after login

The more we go further, the cause of the error in the code at the beginning of the article has been found. Why can it be solved by putting parentheses? Simply put, () converts a statement into an expression, called a statement expression. The code in parentheses will be converted into expression evaluation and returned. The object literal must exist as an expression.

This article will not talk about expressions. One thing worth remembering is that expressions always have a return value. Most expressions will be wrapped in (), and the parentheses cannot be empty. If there are multiple expressions, separated by commas, which is the so-called comma expression, the value of the last one will be returned.

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!