我有以下类型的表,它是动态生成的。我希望以下列格式将其转换为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 :(得分:0)
有一个库将表转换为json格式:https://github.com/lightswitch05/table-to-json
我希望它有所帮助。
答案 1 :(得分: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?