2013-08-02 129 views
0

我有以下类型的表,它是动态生成的。我希望这可以按照以下格式将其转换为JSON。我尝试了各种方法,但徒劳无益。将嵌套表转换为JSON

有人可以帮我告诉我如何使用jQuery来生成这个。

注意:使用for循环动态生成内表。

预计JSON格式:

{"array" : [{"header1":"table1data1","header2":"table1data2","header3":"table1data3" }, 
      {"header1":"table2data1","header2":"table2data2","header3":"table2data3" }, 
      {"header1":"table3data1","header2":"table3data2","header3":"table3data3" } 
      ]} 

表:

<table id="Maintable"> 
<tr> 
<td> 

    <table id="headertable"> 
     <tr><th> header1</th></tr> 
     <tr><th> headr2</th></tr> 
     <tr><th> header3</th></tr> 
    </table> 


</td> 
<td> 
    <table class="innertable" id="innertable1"> 
     <tr><td> table1data1</td></tr> 
     <tr><td> table1data2</td></tr> 
     <tr><td> table1data3</td></tr> 
    </table> 

</td> 
<td> 
    <table class="innertable" id="innertable2"> 
     <tr><td> table2data1</td></tr> 
     <tr><td> table2data2</td></tr> 
     <tr><td> table2data3</td></tr> 
    </table> 

</td> 

... 

<td> 
    <table class="innertable" id="innertable10"> 
     <tr><td> table10data1</td></tr> 
     <tr><td> table10data2</td></tr> 
     <tr><td> table10data3</td></tr> 
    </table> 

</td> 

</tr> 
</table> 

回答

0

后一些谷歌和自我命中和线索,我得到了答案:

 //logic for creating json from html table 
     var myRows = []; 
     var $headers = $("th"); 

     var $tbody = $(".innertable tbody").each(function(index) { 

     $rows = $(this).find("tr:not(:last-child)");// I have some delete buttons in the last td of each column which i dont want so not(:last-child) 
     myRows[index] = {}; 
     $rows.each(function(rowIndex) { 
     myRows[index][$($headers[rowIndex]).html()] = $(this).text(); 
    });  
    }); 

    var myObj = {}; 
    myObj.array= myRows; 
    //alert(JSON.stringify(myObj)); 

refrence:How to convert the following table to JSON with javascript?