JQuery解析json数据
1 <script> 2 var data ="{" + 3 "root:[" + 4 "{name:'1',value:'0'}," + 5 "{name:'6101',value:'北京市'}," + 6 "{name:'6102',value:'天津市'}," + 7 "{name:'6103',value:'上海市'}," + 8 "{name:'6104',value:'重庆市'}," + 9 "{name:'6105',value:'渭南市'}," + 10 "{name:'6106',value:'延安市'}," + 11 "{name:'6107',value:'汉中市'}," + 12 "{name:'6108',value:'榆林市'}," + 13 "{name:'6109',value:'安康市'}," + 14 "{name:'6110',value:'商洛市'}" + 15 "]}"; 16 17 var dataObj = eval("("+data+")");//转换为json对象 18 alert(dataObj.root.length);//输出root的子对象数量 19 20 $.each(dataObj.root,function(idx,item){ 21 if(idx==0){ 22 return true; 23 } 24 //输出每个root子对象的名称和值 25 console.log("name:"+item.name+",value:"+item.value); 26 }); 27 </script>
定义一个json格式的字符串data.
对于服务器返回的JSON字符串,如果jquery异步请求没做类型说明,或者以字符串方式接受,
那么需要做一次对象化处理,方式不是太麻烦,就是将该字符串放于eval()中执行一次。这种方式也适合以普通javascipt方式获取json对象.
转成对象后,然后遍历取值就OK。