The parsing of JSON in jquery

  • 2020-05-16 06:19:14
  • OfStack

Considering that the server returns a string in the form of JSON, it is much the same with the JSON object encapsulated by a plug-in such as JSONObject, which is not explained here.


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 '}
]
}";

Here, based on the data types obtained asynchronously by jquery -- json objects and strings, the result processing methods obtained by the two methods are introduced respectively.

1. For the JSON string returned by the server, if the jquery asynchronous request is not typed or accepted as a string, it needs to be objectified once, either by too much trouble or by placing the string in eval() once. This method is also suitable for obtaining json objects in the normal javascipt way, as illustrated by the following examples:


var dataObj=eval("("+data+")");// convert json object
alert(dataObj.root.length);// The output root The number of child objects
$.each(dataObj.root,fucntion(idx,item){
if(idx==0){
return true;
}
// The output of each root The name and value of the child object
alert("name:"+item.name+",value:"+item.value);
})

Note: for 1-like js to generate json objects, simply replace the $.each () method with an for statement, all else being equal.

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


$.getJSON("http://user.qzone.qq.com/2227211070",{param:"gaoyusi"},function(data){
// Returned here data Is already json object
// The following other operations are the same 1 Kind of circumstance
$.each(data.root,function(idx,item){
if(idx==0){
return true;// with countinue To return to false with break
}
alert("name:"+item.name+",value:"+item.value);
});
});

That's all for jQuery parsing json in this article. I hope you enjoy it.


Related articles: