html table表数据转Json格式示例代码
网站建设 2021-07-02 22:42www.dzhlxh.cn网站建设
<table>表数据转 Json 格式的javascript函数如下
<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>
复制代码
代码如下:<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>