An example of how jquery JSON is parsed

  • 2020-03-30 03:35:15
  • OfStack

All the considerations here are that the server returns a string in the form of JSON, which is similar to the JSON object encapsulated by a plug-in such as JSONObject.

The JSON string set is first shown here, and the string set is as follows:


var data=" 
{ 
root: 
[ 
{name:'1',value:'0'}, 
{name:'6101',value:' Xi 'an '}, 
{name:'6102',value:' Tongchuan city '}, 
{name:'6103',value:' baoji '}, 
{name:'6104',value:' xianyang '}, 
{name:'6105',value:' weinan '}, 
{name:'6106',value:' Yan 'an '}, 
{name:'6107',value:' Grassland, '}, 
{name:'6108',value:' Yulin city '}, 
{name:'6109',value:' Ankang municipality '}, 
{name:'6110',value:' shangluo '} 
] 
}";

  Based on the data types obtained asynchronously by jquery -- json objects and strings, this paper introduces the result processing methods obtained in two ways.

1. If the JSON string returned by the server is not typed or accepted as a string by the jquery asynchronous request, it needs to be objectized once, either by placing the string in eval() and executing it once. This method is also suitable for the common javascript method to obtain json objects, the following examples:


var dataObj=eval("("+data+")");//Convert to a json object
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 a normal js generated json object, just replace the $.each() method with a for statement, and the rest remains the same.

2. For the server returns a JSON string, if the jquery asynchronous request will type (generally) for this configuration attribute set to "JSON", or use $. GetJSON () method to obtain the server returns, so there is no need for the eval () method, because this time the result is a JSON object, simply call the object can be directly, here to $. GetJSON method for example data processing methods:

$. GetJSON (" http://gaoyusi.blog.163.com/ ", {param: "gaoyusi}", function (data) {


//The data returned here is already a json object
//The following other operations are the same as the first case
$.each(data.root,function(idx,item){ 
if(idx==0){ 
return true;//Countinue returns false as a break
} 

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

}); 
});

Related articles: