Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

JavaScript transformation and parsing JSON method instances are explained in detail


May 08, 2021 JSON


Table of contents


JavaScript transforms and parses JSON

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

One is to use the eval() function.


Use the Fusion object for return resolution.


Using the eval function to parse, jquery's each method traverses


Using JQuery's method of parsing JSON data, as the transfer object of JQuery's asynchronous request, the result returned after JQuery's request is the json object, which is considered here in the form of a string returned by the server in the form of JSON, and for the JSON object encapsulated by plug-ins such as JSONObject, which is much the same, no more explanations are given here.


The JSON string set is given first, as follows:
var data="{
root:
[
    {name:'1',value:'0'},
    {name:'6101',value:'北京市'},
    {name:'6102',value:'天津市'},
    {name:'6103',value:'上海市'},
    {name:'6104',value:'重庆市'},
]
}";

Based on JQuery's asynchronously acquired data type, the json object and the string, here is an introduction to how the results obtained are handled in two ways.


The first method:

eval()

For a JSON string returned by the server, if the jquery asynchronous request is not typed or accepted as a string, an objectification processing is required either too cumbersome or the string is executed once in the eval(). This approach is also suitable for obtaining jason objects in a normal javascipt manner, as explained below:

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

Why eval is to be added here ("(""""""""""" What about it?

The reason is: the problem with eval itself. Since json starts and ends with a "

The purpose of bracketing is to force the eval function to force the expression in parentheses to be converted into an object when dealing with JavaScript code, rather than executing it as a statement. A s an example, such as the object literally, if the outer brackets are not added, then eval will recognize braces as the start and end tags of the JavaScript block of code, then the word "" will be considered to have executed an empty statement. So the following two execution results are different:
// return undefined

alert(eval("{}");

// return object[Object]

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

For this writing, in JS, you can see it everywhere. e .g.: (function()) W hen 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 a typical js-generated jason object, you only need to replace the $.each() method with a for statement, and the rest does not change, the JSON string returned by the server.

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

Method, because the result is already a jason object, just call the object directly, here is the $.getJSON method 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);

    });

});

It is particularly important to note here that the eval() method in Mode 1 is dynamically executed in which the string (possibly the js script) is executed, which can easily cause system security problems. S o you can use 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 approach:

The parsing method is done using the Fusion object, and its typical application is the resolution of the return data, such as success under the AJAX method in JQuery.

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

At this point the data is a json object that will be parsed.