HTML5已原生支持json的解析,window.JSON.parse()将baijson格式字符串du转换为json对象,window.JSON.stringify()将json对象转换为json格式字符串。
示例:bai Html代码 <!duDOCTYPE HTML> <html> <head> <title>Window.JSON</title> <meta charset="gb18030"> </head> <body> <button type="button" id="btn1">解析json字符串</button> <button type="button" id="btn2">json对象转换为json字符串</button> <div id="res"> </div> <script language="JavaScript"> <!-- var jsonStr = "{\"total\":100,\"data\":[{\"id\":10001,\"name\":\"scott\"},{\"id\":10002,\"name\":\"tiger\"}]}"; var jsonObj = window.JSON.parse(jsonStr); document.getElementById("btn1").onclick = function() { var str = "json字符串解析为json对象"; str += "<span>Total:"+jsonObj.total+"</span><span>Data:"; for (var i=0;i<jsonObj.data.length ; i++) { str += "id:" + jsonObj.data[i].id + ",name:" + jsonObj.data[i].name+""; } str += "</span>"; document.querySelector("#res").innerHTML = str; } document.getElementById("btn2").onclick = function() { var jsonObj = {total:100,data:[{id:10001,name:"scott"},{id:10002,name:"tiger"}]}; var jsonStr = window.JSON.stringify(jsonObj); var str = "转为json字符串:" + jsonStr; document.querySelector("#res").innerHTML = str; } //--> </script> </body> </html>