JS parses json using eval

Source: Internet
Author: User
Tags closure eval function definition json object object opening and closing tags

The

 eval usage eval function receives an argument s, and if S is not a string, it returns directly to S. Otherwise execute the S statement, here is an example of eval parsing JSON

First of all, the use of eval, the content is relatively simple, familiar can skip the Eval function to receive a parameter s, if S is not a string, then directly return S. Otherwise execute the S statement. If the S statement executes the result is a value, this value is returned, otherwise the undefined is returned. Of particular note is that the object declaration syntax "{}" does not return a value, it needs to be enclosed in parentheses to return the value, a simple example is as follows: The     code is as follows: Var s1= ' "A" + 2 '; expression var s2= ' {a:2} '; Statement alert (eval (S1)); -> ' A2 ' Alert (eval (S2)); ->undefined Alert (eval (' + s2 + ')); ->[object object]      You can see that for an object declaration statement, it is simply execution and cannot return a value.   to return an object declaration statement such as the usual "{}", you must enclose it in parentheses to convert it to an expression to return its value. This is one of the fundamentals of using JSON for AJAX development. As you can see clearly in the example, the second alert statement outputs the undefined, and the third with parentheses is the object that the statement represents.   Now the focus of this article is how to execute global code within a function. To illustrate this issue, first look at an example: the   code is as follows: Var s= ' global '; Defines a global variable function demo1 () {    eval (' var s= ' local ');} demo1 (); alert (s); ->global      It is well understood that the DEMO1 function above is equivalent to: function Demo1 () {var s= ' local ';}, which defines a localized variable s.   So the final output is global is not a strange thing, after all, we can clearly distinguish between local and global variables.   Carefully, you can see that the eval function is always executed within the context variable space (also known as a package, closure) that calls it, whether it is a variable definition or a function definition, so the following code produces an error that is not defined by the function: The   code is as follows: var s= ' function test () {return 1;} '; A function definition statement funCtion Demo2 () {    eval (s);} demo2 (); Alert (test ()); ->error:test is not defined     This is because the test function is defined in the local space and can be accessed outside of the DEMO2 function.   Sharing: Parsing the note points in JSON with JS Eval in JS, the string in JSON is parsed into JSON data format, usually in two ways:   1. One is to use the Eval () function.   2. Use a function object to return resolution.   Using the Eval function to parse, and using each of the jquery methods to traverse   Parse JSON data in jquery, as the transmission object of the jquery asynchronous request, the result of the jquery request returned is the JSON object, Here the server returns the form of a JSON-like string, which is similar to a JSON object encapsulated by a plug-in such as Jsonobject, which is no longer explained here.   Here we first give a set of JSON strings, the string set is as follows:     code is as follows: Var data= "  {  root:  [  {name: ' 1 ', Value: ' 0 '},   {name: ' 6101 ', Value: ' Beijing '},  {name: ' 6102 ', Value: ' Tianjin '},  {name: ' 6103 ', Value: ' Shanghai '},  {name: ' 6104 ', Value: ' Chongqing '},  {name: ' 6105 ', Value: ' Weinan '},  {name: ' 6106 ', Value: ' Yanan '},  {name: ' 6107 ', Value: ' Hanzhong '},  {name: ' 6108 ', Value: ' Yulin '},  {name: ' 6109 ', Value: ' Ankang '},  {name: ' 6110 ', Value: ' Shangluo '} ]} ' ;      This is based on the data type--json object and string that jquery asynchronously obtains, and describes the result processing methods obtained in two ways respectively.   1. For the server returned JSOn string, if the jquery asynchronous request does not have a type description, or is accepted as a string, it is necessary to do an object-by-case, either in a cumbersome way, or to put the string in eval () once. This is also a good way to get a JSON object in a normal javascipt way, with the following examples:   var dataobj=eval ("(" +data+) ");//Convert to JSON object   Why eval here to add" ("+ Data+ ")"?   The reason for this is that the eval itself is a problem. Since JSON starts and ends with "{}", in JS it is treated as a block of statements, so it must be coerced into an expression. The purpose of   plus parentheses is to force the Eval function to force an expression in parentheses (expression) into an object when processing JavaScript code instead of executing as a statement (statement). For example, an object literal {}, if the outer bracket is not added, Eval recognizes the curly braces as the opening and closing tags of the JavaScript code block, then {} will be considered to have executed an empty statement. So the following two execution results are different: The     code is as follows: Alert (eval ("{}");//return undefined alert (eval ({}));/return Object[object] & nbsp   for this type of writing, in JS, you can see everywhere.   such as: (function ()) {} ();   When doing closure operation.   Code as follows: Alert (dataObj.root.length);//output root number of child objects   $.each (dataobj.root,fucntion (Idx,item) {  if (idx= =0) {  return true; } //Output the name and value of each root child   alert ("Name: +item.name+", Value: "+item.value");        NOTE: To generate a JSON object for a generic JS, simply replace the $.each () method with the For statement, and the other unchanged.   2. For the JSON string returned by the server, if JqueRY asynchronous requests set the type (typically this configuration property) to "JSON", or use the $.getjson () method to get the server back, then the eval () method is not needed because the result is already a JSON object, just call the object directly, here with $. The Getjson method is used to illustrate the data processing method:    code as follows: $.getjson ("http://www.xx.cn/", {param: "Gaoyusi"},function (data) { // The data returned here is already a JSON object  //The following other operations with the first case   $.each (data.root,function (Idx,item) {  if (idx==0) {  return true;//with Countinue, returns false with break }  alert ("Name: +item.name+", Value: "+item.value); }"); });       It is particularly important to note that the eval () method in mode 1 is dynamically executing the string (possibly the JS script), which can easily cause a system security problem. So you can use a few Third-party client script libraries that circumvent eval (), such as JSON in JavaScript, which provides a script library of no more than 3k.   The second solution is to use a function object to complete, its typical application is in jquery in the Ajax method of success, etc. for the return data analysis       code as follows: Var json= ' { "Name": "CJ", "Age": 18} ';   data = (new Function ("", "Return" +json)) ();         At this time data is a will parse into a JSON object to the  

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.