使用eval将json字符串转换为json对象并且处理json数据
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE> New Document </TITLE> <META NAME="Generator" CONTENT="EditPlus"> <META NAME="Author" CONTENT=""> <META NAME="Keywords" CONTENT=""> <META NAME="Description" CONTENT=""> <!--- date:2011/6/29 23:30 author:天下太平 --> <script src="jquery-1.3.2.js"></script> <script> $(function () { $("#loaddata").click(function () { //json字符串数据 var json = '{"employees" :[{"name" : "ZhangSan","sex" : " man","age" : "10","city" : "beijing","state" : "china","department" : "it"},{"name" : "lisi","sex" : "wumen","age" :"20","city" : "shanghai","state" : "china","department" : "it"}]}'; //json数据类型 var jsonobj = eval('(' + json + ')'); var html = ''; //employees子对象数量 var jobjLength = jsonobj.employees.length; //遍历json对象 $.each(jsonobj.employees, function (i, item) { html += '<tr><td>' + item.name + '</td>' + '<td>' + item['sex'] + '</td>' + '<td>' + item.age + '</td>' + '<td>' + item.city + '</td>' + '<td>' + item.state + '</td>' + '<td>' + item.department + '</td></tr>'; }); $('#title').after(html); }); $("#loaddata1").click(function () { //json字符串数据 var sjson ='{"employees" : {"field" : ["name","sex","age","city","state","department"],"value" :[["ZhangSan","Male","30","BeiJing","China","IT"],["LiSi","Female","20","ShangHai","China","IT"]]}}'; //json数据类型 var jsonobj = eval('(' + sjson + ')'); var html = ''; //employees子对象数量 var jobj = jsonobj.employees.value; var jobjlength = jobj.length; //遍历json对象 $.each(jobj, function (i, item) { html += '<tr><td>' + item[0] + '</td>' + '<td>' + item[1] + '</td>' + '<td>' + item[2] + '</td>' + '<td>' + item[3] + '</td>' + '<td>' + item[4] + '</td>' + '<td>' + item[5] + '</td></tr>'; }); $('#title').after(html); }); }); </script> </HEAD> <input type="button" value="加载数据" id="loaddata" /> <input type="button" value="加载简化json数据" id="loaddata1" /> <BODY> <table id="infotable" > <tr id="title"><th>name</th><th>sex</th><th>age</th><th>city</th><th>state</th><th>department</th></tr> </table> </BODY> </HTML>