1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>json解析</title> <link rel="stylesheet" type="text/css" href="layui/css/layui.css"/> </head> <body> <table class="layui-table" style="width: 500px !important;"> <tr> <th>编号</th> <th>姓名</th> <th>年龄</th> <th>性别</th> <th>操作</th> </tr> </table> </body> </html> <script src="js/jquery-3.5.1.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
var jsonStr = '[{"id":1,"name":"张三","age":20,"sex":"男"}, {"id":2, "name":"李四","age":28,"sex":"男"}, {"id":3,"name":"王五","age":23,"sex":"男"}, {"id":4,"name":"赵六","age":30,"sex":"男"}]'; console.log(jsonStr);
var arr = JSON.parse(jsonStr); console.log(arr); var str2 = '{"status":200, "totalCount":100, "message":"请求成功!", "data":[{"id":1,"name":"张三","age":20,"sex":"男"}, {"id":2, "name":"李四","age":28,"sex":"男"}, {"id":3,"name":"王五","age":23,"sex":"男"}, {"id":4,"name":"赵六","age":30,"sex":"男"}]}'; var obj = JSON.parse(str2); console.log(obj); console.log(obj.status); console.log(obj.totalCount); console.log(obj.message); var dataArray = obj.data; for(var i in dataArray){ var tr = document.createElement("tr") $("table").append(tr);
var s = dataArray[i]; var td1 = document.createElement("td"); $(td1).html(s.id); $(tr).append(td1); var td2 = document.createElement("td"); $(td2).html(s.name); $(tr).append(td2); var td3 = document.createElement("td"); $(td3).html(s.age); $(tr).append(td3); var td4 = document.createElement("td"); $(td4).html(s.sex); $(tr).append(td4); var td5 = document.createElement("td"); $(td5).html("<button class='layui-btn layui-btn-warm layui-btn-sm'>编辑</button><button class='layui-btn layui-btn-normal layui-btn-sm'>删除</button>"); $(tr).append(td5); } var s1 = JSON.stringify(arr); console.log(s1); var s2 = JSON.stringify(obj); console.log(s2); </script>
|