JS parsing json using eval (using JSON in JS) _javascript tips

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

First, the use of eval, the content is relatively simple, familiar can skip
The Eval function receives an argument s, and if S is not a string, it returns directly to 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. A special note is that the object declaration syntax "{}" does not return a value, which needs to be enclosed in parentheses to return the value, as the simple example reads:

Copy Code code as follows:

var s1= ' "A" + 2 '; An expression
var s2= ' {a:2} '; Statement
Alert (eval (S1)); -> ' A2 '
Alert (eval (S2)); ->undefined
Alert (eval (' + s2 + ')); ->[object Object]

As you can see, for an object declaration statement, it is simply execution and cannot return a value.

In order 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, let's look at an example:

Copy Code code as follows:

var s= ' global '; Define a global variable
function Demo1 () {
Eval (' var s= ' local ');
}
Demo1 ();
alert (s); ->global

Well understood, 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.
With a closer look, you can see that the eval function is always executed within the context variable space (also known as: Package, closure) that calls it, whether it is a variable definition or a function definition, so the following code produces an error that is undefined by the function:

Copy Code code 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 within the DEMO2 function and is inaccessible outside.

Sharing: Using JS eval to parse the points of attention in JSON
There are generally two ways to parse a JSON string into a JSON data format in JS:

1. One is to use the Eval () function.

2. Use function objects to perform return parsing.

Use the Eval function to parse, and use each of the jquery methods to traverse the

The method of parsing JSON data in jquery, as the transmission object of the jquery asynchronous request, returns the result of the jquery request as a JSON object, taking into account the form of a string returned by the server in JSON form. The same is the case with JSON objects encapsulated by plug-ins such as Jsonobject, which are no longer described here.
Here we first give a set of JSON strings, and the string set is as follows:

Copy Code code as follows:

var data= "
{
Root
[
{name: ' 1 ', Value: ' 0 '},
{name: ' 6101 ', Value: ' Beijing '},
{name: ' 6102 ', Value: ' Tianjin '},
{name: ' 6103 ', Value: ' Shanghai City '},
{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 JSON string returned by the server, 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 JSON objects in a normal Javascipt way, as illustrated in the following example:

var dataobj=eval ("(" +data+ ")");//Convert to JSON object

Why do I have to eval here to add "(" ("+data+"));/"?

The reason is that 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 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:

Copy Code code as follows:

Alert (eval ("{}");//return undefined
Alert (eval ({}));/return Object[object]

For this type of writing, in JS, you can see everywhere.

such as: (function ()) {} (); When doing closure operation.

Copy Code code as follows:

Alert (dataObj.root.length)//output The number of child objects of root
$.each (Dataobj.root,fucntion (Idx,item) {
if (idx==0) {
return true;
}
Output the name and value of each root child object
Alert ("Name: +item.name+", Value: "+item.value");
})

Note: For the general JS generation JSON object, only need to replace the $.each () method with the For statement, the other unchanged.

2. For the JSON string returned by the server, the eval () method is not required if the jquery asynchronous request sets the type (typically this configuration property) to "JSON" or uses the $.getjson () method to get the server back. Because the result is already a JSON object, just call the object directly, and here take the $.getjson method as an example to illustrate the data processing method:

Copy Code code as follows:

$.getjson ("http://www.xx.cn/", {param: "Gaoyusi"},function (data) {
The data returned here is already a JSON object
The following other actions are the same as 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");
});
});

In particular, it is important to note that the eval () method in mode 1 executes the string (possibly the JS script) dynamically, 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 way to do this is to use a function object to do it, and it's typical application is the success of the Ajax method in jquery to the return data

Copy Code code as follows:

var json= ' {' name ': ' CJ ', ' Age ': 18} ';

data = (New Function ("", "Return" +json)) ();


The data at this point is the one that will parse into a JSON object.

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.