A minor problem with Eval parsing the JSON string in JS

  • 2020-12-26 05:35:01
  • OfStack

I wrote an introduction to JSON in which I talked about the parsing of JSON. As we all know, advanced browsers can use JSON.parse () API to parse an JSON string into JSON data, or, slightly worse, the eval() function.

JSON (JavaScript Object Notation) a simple data format that is lighter and lighter than xml. JSON is the JavaScript native format, which means that no special API or toolkit is required to process JSON data in JavaScript.

The rule of JSON is simple: an object is an unordered collection of "name/value pairs". 1 object begins with "{" (left parenthesis) and ends with"} "(right parenthesis). Each "name" is followed by a ":" (colon); Use ", "(comma) between" name/value "pairs


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

Did you notice that the str variable is wrapped with a layer of braces when passing arguments to eval()? Why do you do this?

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

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

Simply put, the argument to the eval function is a string, and if the string "noString" is processed, the result will be a normal, runnable JavaScript statement.

How do you say? Take chestnuts, for example:


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

"hello world" pops up after execution. We made the str variable "noString", and the rough way to do it was to remove the quotes from the outside, adjust the inside (escape, etc.), and then it became:


alert('hello world')

very good! This is a normal working JavaScript statement! Run!

Going back to the beginning question, why does the JSON string have curly braces. If not, it looks like this:


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

Yes, that's a mistake. Why did it report an error? Try str "noString", execute 1:


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

Without a doubt, an JSON object or an object is not an 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 add "" to name and error again?


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

Ok, I'm getting dizzy, but you can still make str "nostring" and see if it executes properly. The results of the former are:


{name: "hanzichi"}

This is indeed a valid JavaScript statement. {} We can use it not only in scenarios like if, for statements, and so on, but even at any time, because before ES6 JavaScript only had block-level scope, so there was no conflict with scope or anything like that. name: "hanzichi" after removing {} is also a valid statement, 1 label statement, label statement is very useful in breaking out of the nested loop, specific can refer to label, and as the tag of label statement, name is not quoted, the tag can be placed anywhere in the JavaScript code, it does not matter if it is not used.

Once an object has two key, such as {name: "hanzichi", age: 10}, ok, two label statements? Think of "hanzhichi" and "10" as statements, but they can only be connected with a seal! Use commas between expressions. So it's ok to change it to the following:


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

The reason for the error in the code at the beginning of the article is found. Why can it be solved by enclosing parentheses? In simple terms, () converts statements into expressions, called statement expressions. The code in parentheses is converted to expression evaluation and returned, and object literals must exist as expressions.

This article won't talk much about expressions, but refer to the link at the end of the article. One thing to remember is that an expression always has a return value. Most expressions are enclosed in (), parentheses cannot be empty, and if there are multiple expressions separated by commas, the so-called comma expression will return the last value.

Above is the site to you to introduce JS Eval parsing JSON string 1 small problem, I hope to help you!


Related articles: