In javascript eval parses JSON strings

  • 2021-01-14 05:34:12
  • OfStack

As we all know, advanced browsers can use JSON.parse () API to parse an ES4en string into ES5en data. For a slightly less elegant 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}

Did you notice that when passing arguments to eval(), the str variable is surrounded by a layer of braces? Why do you do that?

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

The argument to 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 declaration. Do not call eval() to evaluate arithmetic expressions; JavaScript automatically evaluates arithmetic expressions.

In short, the eval function takes a string. If you "noString" the string, you will get a normal, working JavaScript statement.

How do you say? For example, code like this:


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

After execution, "hello world" pops up. We convert the str variable to "noString", which is roughly done by removing the outside quotes and adjusting the inside (escaping, etc.), and this becomes:


alert('hello world')

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

Back to the original question of why the JSON string is wrapped in braces. If not, it looks like this:


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

Well, there's an error. Why is the error reported? Try to make str "noString" as str.


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

There is no doubt that an 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 gives an error?


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

str "nostring" can be used to execute the JavaScript statement correctly. The result of the former:


{name: "hanzichi"}

This is indeed a valid JavaScript statement. {} can be used not only in if, for statements, etc., but even at any time. Since JavaScript prior to ES6 only had blocklevel scopes, there is no conflict with scopes. label is a very useful statement for breaking out of nested loops. For details, refer to label. As a notation for label statements, name cannot be enclosed in quotes.

For example, {name: "hanzichi", age: 10}, ok, two label statements per object? Think of "hanzhichi" and "10" as statements, but they can only be connected by seals! (You can only use commas between expressions). So it's OK to change it to something like this:


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

More and more, the cause of the error in the code at the beginning of the article is found, why put a bracket can solve it? Simply put, () converts a statement into an expression, called a statement expression. Any code in parentheses is converted to an expression evaluation and returned. Object literals must exist as expressions.

This article won't talk much about expressions, but it's worth remembering that expressions always return one value. Most expressions are wrapped in (), parentheses cannot be empty, and if there are more than one expression separated by commas, also known as comma expressions, the value of the last one will be returned.


Related articles: