js json:
JSON.parse() //转为json对象。
JSON.stringify() //转为JSON字符串。
举例:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>js json举例</title> </head> <body> <p id="demo"></p> <script> var text = '{ "date" : [' + '{ "key":"info1" , "valmain":"main_info1" },' + '{ "key":"info2" , "valmain":"main_info2" },' + '{ "key":"info3" , "valmain":"main_info3" } ]}'; jsonobj = JSON.parse(text); document.getElementById("demo").innerHTML ="-->"+ jsonobj.date[2].key + " " + jsonobj.date[2].valmain; </script> </body> </html>
结果:-->info3 main_info3
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>js json举例</title> </head> <body> <p id="demo"></p> <script> var text = '{ "date" : [' + '{ "key":"info1" , "valmain":"main_info1" },' + '{ "key":"info2" , "valmain":"main_info2" },' + '{ "key":"info3" , "valmain":"main_info3" } ]}'; jsonstr = JSON.stringify(text); document.getElementById("demo").innerHTML ="-->"+ jsonstr; </script> </body> </html>
结果:-->"{ \"date\" : [{ \"key\":\"info1\" , \"valmain\":\"main_info1\" },{ \"key\":\"info2\" , \"valmain\":\"main_info2\" },{ \"key\":\"info3\" , \"valmain\":\"main_info3\" } ]}"
举例二:重点常用:
存储:
sessionStorage.setItem("userInfo",JSON.stringify(this.$userInfo));
跳转后获取:
var userInfo = JSON.parse(sessionStorage.getItem("userInfo"));