【问题标题】:Converting nested tables to JSON将嵌套表转换为 JSON
【发布时间】:2013-08-06 20:33:33
【问题描述】:

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

【问题讨论】:

    标签: jquery json html-table


    【解决方案1】:

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

    希望对你有帮助。

    【讨论】:

    • 感谢您的链接。但是我想要一些可以明智地读取数据而不是按行读取数据的东西。我猜这个插件是按行阅读的。而且我还有这个插件不读取的内表。
    【解决方案2】:

    经过一番谷歌和自我打击后,我得到了答案:

         //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));
    

    参考:How to convert the following table to JSON with javascript?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-15
      • 2020-05-13
      • 2020-02-20
      • 2017-06-01
      • 2017-11-22
      • 2021-11-25
      • 2015-12-15
      相关资源
      最近更新 更多