html table表數(shù)據(jù)轉(zhuǎn)json格式示例代碼

字號:


    <table>表數(shù)據(jù)轉(zhuǎn) json 格式的javascript函數(shù)如下
    代碼如下:
    <script>
    var keysarr = new array(key0, key1,key2);
    function tabletojson(tableid) { //tableid是你要轉(zhuǎn)化的表的表名,是一個(gè)字符串,如example
    var rows = document.getelementbyid(tableid).rows.length; //獲得行數(shù)(包括thead)
    var colums = document.getelementbyid(tableid).rows[0].cells.length; //獲得列數(shù)
    var json = [;
    var tdvalue;
    for (var i = 1; i < rows; i++) { //每行
    json += {;
    for (var j = 0; j < colums; j++) {
    tdname = keysarr[j]; //json數(shù)據(jù)的鍵
    json += \; //加上一個(gè)雙引號
    json += tdname;
    json += \;
    json += :;
    tdvalue = document.getelementbyid(tableid).rows[i].cells[j].innerhtml;//json數(shù)據(jù)的值
    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>