Converts a JSON string to a JSON object (eval (), New Function ()) in JS

Source: Internet
Author: User
Tags eval opening and closing tags

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.

The first parsing method is resolved using the Eval function and using 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:

The code is as follows Copy Code

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 JSON string returned by the server, if the jquery asynchronous request does not have a type description, or is accepted as a string, it needs to be done at once, either in a cumbersome manner or in an eval (). This is also a good way to get JSON objects in a normal Javascipt way, as illustrated in the following example:

The code is as follows Copy Code
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:

The code is as follows Copy Code

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.

The code is as follows Copy Code

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);
})

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:

The code is as follows Copy Code
$.getjson ("http://www.111cn.net/", {param: "Snsgou"}, 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 (index, item) {
if (index = = 0) {
return true; Same countinue, return 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 type of parsing: Using a Function object to perform, its typical application is in jquery in the Ajax method of success, etc. for the return data analysis

The code is as follows Copy Code

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.