Home  >  Article  >  Web Front-end  >  A small problem with Eval parsing JSON strings in JS_javascript skills

A small problem with Eval parsing JSON strings in JS_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:14:311573browse

I wrote an introductory article about JSON before, which talked about the parsing of JSON. 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.

JSON (JavaScript Object Notation) is a simple data format that is more lightweight than xml. JSON is a native JavaScript format, which means that processing JSON data in JavaScript does not require any special API or toolkit.

The rules of JSON are simple: an object is an unordered collection of "name/value" pairs. An object starts with "{" (left bracket) and ends with "}" (right bracket). Each "name" is followed by a ":" (colon); "name/value" pairs are separated by "," (comma)

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

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);

"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')

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 :

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

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

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

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); 

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"}

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

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. For expressions, you can refer to the link at the end of the article. It's worth remembering 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.

The above is a small problem that the editor introduces to you about Eval parsing JSON strings in JS. I hope it will be helpful to everyone!

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