JQuery解析json数据

时间:2022-01-23 22:07:43
 <script>
var data ="{" +
"root:[" +
"{name:'1',value:'0'}," +
"{name:'6101',value:'北京市'}," +
"{name:'6102',value:'天津市'}," +
"{name:'6103',value:'上海市'}," +
"{name:'6104',value:'重庆市'}," +
"{name:'6105',value:'渭南市'}," +
"{name:'6106',value:'延安市'}," +
"{name:'6107',value:'汉中市'}," +
"{name:'6108',value:'榆林市'}," +
"{name:'6109',value:'安康市'}," +
"{name:'6110',value:'商洛市'}" +
"]}"; var dataObj = eval("("+data+")");//转换为json对象
alert(dataObj.root.length);//输出root的子对象数量 $.each(dataObj.root,function(idx,item){
if(idx==0){
return true;
}
//输出每个root子对象的名称和值
console.log("name:"+item.name+",value:"+item.value);
});
</script>

  定义一个json格式的字符串data.

  对于服务器返回的JSON字符串,如果jquery异步请求没做类型说明,或者以字符串方式接受,

那么需要做一次对象化处理,方式不是太麻烦,就是将该字符串放于eval()中执行一次。这种方式也适合以普通javascipt方式获取json对象.

  转成对象后,然后遍历取值就OK。