Detailed explanation of JavaScript conversion and parsing JSON method examples

Detailed explanation of JavaScript conversion and parsing JSON method examples

JavaScript converts and parses JSON

There are generally two ways to parse JSON strings into JSON data format in JavaScript:

One is to use the eval() function .

Use the Function object for return parsing.

Use the eval function to parse, jquery's each method to traverse

The method of parsing JSON data with JQuery, as the transmission object of JQuery asynchronous request, the result returned after JQuery request is a json object, the form of the string returned by the server in JSON form is considered here, for the JSON object encapsulated by plug-ins such as JSONObject , which is similar to this, and will not be explained here.


Here, the JSON string set is given first, and the string set is as follows:

var data="{
root:
[
    {name:'1',value:'0'},
    {name:'6101',value:'北京市'},
    {name:'6102',value:'天津市'},
    {name:'6103',value:'上海市'},
    {name:'6104',value:'重庆市'},
]
}";

Based on the data types acquired asynchronously by JQuery - json objects and strings, the processing methods of the results obtained by the two methods are introduced respectively.


the first method:

eval()

For the JSON string returned by the server, if the jquery asynchronous request does not specify the type, or accepts it as a string, then it needs to be objectified. The method is not too troublesome, just put the string in eval() and execute it once . This method is also suitable for obtaining json objects in the ordinary javascipt way, as illustrated in the following example:

// 转换为json对象
var dataObj=eval("("+data+")");

Why do you want to add ("("+data+")"); here?

The reason is: the problem of eval itself. Since json starts and ends with "{}", in JS, it will be treated as a statement block, so it must be converted into an expression forcibly.

The purpose of adding parentheses is to force the eval function to convert the expression inside the brackets into an object when processing JavaScript code, rather than executing it as a statement. To give an example, such as the object literal {}, if the outer brackets are not added, then eval will recognize the curly brackets as the start and end markers of the JavaScript code block, then {} will be considered to execute an empty statement. So the following two execution results are different:

// return undefined

alert(eval("{}");

// return object[Object]

alert(eval("({})");

For this way of writing, in JS, you can see it everywhere. Such as: (function()) {}(); when doing closure operations, etc.

//输出root的子对象数量

alert(dataObj.root.length);

$.each(dataObj.root,fucntion(idx,item){

    if(idx==0){

        return true;

    }

    //输出每个root子对象的名称和值

    alert("name:"+item.name+",value:"+item.value);

})

For general js to generate json objects, you only need to replace the $.each() method with a for statement, and the other remains unchanged, the JSON string returned by the server.

For the JSON string returned by the server, if the jquery asynchronous request sets the type (usually this configuration property) to "json", or uses the $.getJSON() method to obtain the server's return, then eval() is not required

method, because the result obtained at this time is already a json object, you only need to call the object directly. Here, the $.getJSON method is used as an example to illustrate the data processing method:

$.getJSON("http://www.phpzixue.cn/",{param:"gaoyusi"},function(data){

    //此处返回的data已经是json对象

    //以下其他操作同第一种情况

    $.each(data.root,function(idx,item){

        if(idx==0){

            //同countinue,返回false同break

            return true;

        }

        alert("name:"+item.name+",value:"+item.value);

    });

});

What needs special attention here is that the eval() method in method 1 dynamically executes the string (maybe a js script), which can easily cause system security problems. Therefore, some third-party client-side script libraries that avoid eval() can be used. For example, JSON in JavaScript provides a script library of no more than 3k.


The second method: 

The parsing method is to use the Function object to complete, and its typical application is the parsing of the returned data such as success under the AJAX method in JQuery.

var json='{"name":"CJ","age":18}';
data =(new Function("","return "+json))();

The data at this time is one that will be parsed into a json object.

Guess you like

Origin blog.csdn.net/cdming/article/details/130179265