0

我有以下类型的表,它是动态生成的。我希望将其转换为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>
4

2 回答 2

0

有一个将表格转换为 json 格式的库:https ://github.com/lightswitch05/table-to-json

我希望它有帮助。

于 2013-08-02T11:36:06.277 回答
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:如何使用 javascript 将下表转换为 JSON?

于 2013-08-06T12:30:02.730 回答