Simple Introduction: eval and JSON in JS

Source: Internet
Author: User

Statement:

First of all, I am a newbie to JS, So I dare not go into depth. I just share my recent eval learning experience with you. If you are a master, I can skip it.

Suitable for readers:

I have no idea how eval converts a string to a JSON object. When I use eval to convert a string to a JSON object, I often encounter"Missing] After element list"Wrong, but somehow wrong ."

 

1. Introduction to eval (this part comes fromHttp://www.w3school.com.cn/js/jsref_eval.asp)

Definition and usage: the eval () function can calculate a string and execute the JavascriptCode.

Syntax: eval (string)

String: required. The string to be calculated, which contains the Javascript expression to be calculated or the statement to be executed.

Return Value: the value obtained by string calculation (if any ).

Note: This method only accepts the original string as the parameter. If the string parameter is not the original string, this method will be returned without any change. Therefore, do not pass a String object as a parameter for the eval () function. If you try to override the eval attribute or assign the eval () method to another attribute and call it through this attribute, ecmascript can throw an evalerror exception.

Exception: If the parameter does not contain valid expressions and statements, a syntaxerror exception is thrown. If eval () is illegally called, an evalerror error is thrown. If the JavaScript code passed to eval () generates an exception, Eval () will pass the exception to the caller.

 

Ii. Eval usage example

For programming problems, I always think that the best way to illustrate the problem is an example. Let's look at the above definition and look at several examples:

Code 1:

 1   VaR  Code1  =  "  \ "A \" + 2  "  ;
2 VaR Code2 = { " A " : 2 };
3 VaR Code3 = " {\ "B \": 3} " ;
4
5 Console. Log (code1 );
6 Console. Log (eval (code1 ));
7
8 Console. Log (code2 );
9 Console. Log (code2.a );
10 Console. Log (eval (code2 ));
11 Console. Log (eval ( ' ( ' + Code2 + ' ) ' ));
12
13 Console. Log (code3 );
14 Console. Log (code3. B );
15 T = Eval ( ' ( ' + Code3 + ' ) ' );
16 Console. Log (t );
17 Console. Log (T. B );

What will be output from lines 5 to 17? Here is a simple explanation:

Code1 is a string with a numeric expression string. Therefore, the 5th rows are output as "a" + 2, and 6th are output as A2 after eval.

Code2 is a JSON object (for JSON definition reference:In-depth introduction to JSON), So the 8th row output object {A = 2}. If you use alert (code2), [object] will pop up. 9th rows Output 2. Row 10th, because code2 is a JSON object and not a string, Eval does not work here and is returned as is, so it is the same as row 8th output. Row 3: Since code2 is already a JSON object, what is the result of adding a bracket on both sides of the JSON object? This syntax is wrong in JS, so this line will report an exception, if we capture the exception output, it is a headache for new users.Missing] After element list.

Code3 is a JSON string, so the 13th line output is {"B": 3 }. 14th rows output undefined. Line 3 adds parentheses to the string (see the following for the reason of parentheses) and performs eval operations to convert the string into a JSON object. Therefore, line 3 OutputsObject{B=3}, 17th rows output 3.

Check the result:

 

 

Iii. Why should I add brackets to convert a JSON string to a JSON object using eval?

There is an article in the garden.ArticleMake it clear (original article links: eval and JSON). Here we will not be ugly. Here we will explain it directly using the original article.The purpose of parentheses is to force the eval function to forcibly convert the expressions in parentheses into objects when evaluating JavaScript code, rather than executing them as statements. For example, if no outer brackets are added to the object literal {}, Eval identifies the braces as the start and end mark of the JavaScript code block, then {} is considered to have executed an empty statement. The following two execution results are different:

Code 2:

1 Alert (eval ("{}");//Return undefined
2 Alert (eval ("({})");//Return object [object]

Therefore, brackets should be added to the second line of code 1. If this parameter is left blank, you can test it. You can compare this to an SQL statement. When a subquery result is used as an associated table, brackets are added to both sides of the query statement, for example:

Code 3:

SelectTop10*FromTBWhereIDNotIn(SelectTop5IDFromTB)

 

Iv. Processing of Ajax return values in jquery

The most common use of eval to convert a string to a JSON object is in Ajax. Some Ajax return values are strings in JSON format. Therefore, they must be converted using eval ('+ returned JSON format string +'). In this case, writing is generally normal, however, many of them are made using the Ajax method in jquery. The strength of jquery also makes it easy for many people to ignore some problems during use. The more common problems are contenttype and datatype, contenttype has nothing to do with this article. Here we only talk about the datatype parameter.

Datatype can be of the following types: XML, HTML, script, JSON, jsonp, and text. XML, JSON, and text are commonly used. Some friends return the eval value regardless of the type of ype when using it. Sometimes it happens to be right, and sometimes it doesn't know where the problem is.

Datatype is the expected data type returned by the server. If jquery is not specified, responsexml or responsetext is automatically returned Based on the mime information of the http package. That is to say, if your datatype is written in JSON format, jquery has converted the returned value to a JSON object when returning the data, and you do not need to use eval for conversion, if datatype is written in text, Eval conversion is required.

 

I hope this article will be helpful to new users, so that they will not be afraid of eval and JSON. You are welcome to leave a message for discussion.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.