JS解析JSON数据及取值的一些用法时间:2012-12-20%@pagecontentType=text/html;charset=GBKlanguage=java%htmlheadmetahttp-equiv=Content-Typecontent=text/html;charset=gbk/titleJS解析JSON数据/title/headbodystyle=margin:50pxcenterh1bJS解析JSON数据测试界面/b/h1/centerscriptlanguage=javascript//将JSON字符串转换为JSON对象的一些方法//将JSON字符串转换为JSON对象的一些用法(function(){varstr={name:张三,age:20};//JSON对象alert(str.name);alert(str.age);//直接取JSON对象的值//将JSON字符串转换为JSON对象varstr={\name\:\张三\,\age\:\21\};//JSON字符串转义不用系统/和dos一致用\varobj=eval('('+str+')');//使用eval函数将JSON字符串转换为JSON对象alert(obj.name);alert(obj.age);varstr='{name:张三,age:22}';//JSON字符串varobj=(newFunction(return+str))();//使用newFunction()形式将JSON字符串转换为JSON对象alert(obj.name);alert(obj.age);//将JSON对象转换为JSON字符串//varstraa={name:李四,age:20};//JSON对象//varnewJSONtext=straa.toJSONString();//貌似没有原生方法//alert(JSON对象转换为JSON字符串:+newJSONtext);})();//(function(){})();自动执行匿名函数/scriptscript//取值的一些用法//取值的一些用法functionshowJSON(){//效果一varuser={username:andy,age:20,info:{tel:123456,cellphone:98765},address:[{city:beijing,postcode:222333},{city:newyork,postcode:555666}]}alert(user.username);alert(user.age);alert(user.info.cellphone);alert(user.address[0].city);alert(user.address[0].postcode);user.username=Tom;alert(user.username);//效果二varpeople={programmers:[{firstName:Brett,lastName:McLaughlin,email:brett@newInstance.com},{firstName:Jason,lastName:Hunter,email:jason@servlets.com},{firstName:Elliotte,lastName:Harold,email:elharo@macfaq.com}],authors:[{firstName:Isaac,lastName:Asimov,genre:sciencefiction},{firstName:Tad,lastName:Williams,genre:fantasy},{firstName:Frank,lastName:Peretti,genre:christianfiction}],musicians:[{firstName:Eric,lastName:Clapton,instrument:guitar},{firstName:Sergei,lastName:Rachmaninoff,instrument:piano}]}alert(people.programmers[0].firstName++people.programmers[0].email);alert(people.programmers[2].firstName++people.programmers[2].email);alert(people.authors[0].firstName++people.authors[0].genre);alert(people.musicians[1].firstName++people.musicians[1].instrument);}showJSON();/script/body/htmlscripttype=text/javascriptfunctionmm(){varstr=;for(mminwindow.event.srcElement)str+=mm+=+window.event.srcElement[mm]+\n;//得到srcElement的所有属性alert(str);}/script