1. 程式人生 > >table資料轉為json

table資料轉為json

轉自:http://www.ynpxrz.com/n689242c2022.aspx

<script>
var keysArr = new Array("key0", "key1","key2");//可以根據表格的列數新增
function TableToJson(tableid) { //tableid是你要轉化的表的表名,是一個字串,如"example"
var rows = document.getElementById(tableid).rows.length; //獲得行數(包括thead)
var colums = document.getElementById(tableid).rows[0].cells.length; //獲得列數
var json = "[";
var tdValue;
for (var i = 1; i < rows; i++) { //每行
json += "{";
for (var j = 0; j < colums; j++) {
tdName = keysArr[j]; //Json資料的鍵
json += "\""; //加上一個雙引號
json += tdName;
json += "\"";
json += ":";
tdValue = document.getElementById(tableid).rows[i].cells[j].innerHTML;//Json資料的值
if (j === 1) {//第1列是日期格式,需要按照json要求做如下新增
tdValue = "\/Date(" + tdValue + ")\/";
}
json += "\"";
json += tdValue;
json += "\"";
json += ",";
}
json = json.substring(0, json.length - 1);
json += "}";
json += ",";
}
json = json.substring(0, json.length - 1);
json += "]";
return json;
}
</script>