Html表到json数组

时间:2013-08-01 08:24:39

标签: jquery json html-table

我有动态行和列的表,我试图通过循环遍历每个trtd并在文本框中查找值但是没有运气将HTML表转换为Json。这是我的js代码。

 $("#btn_Table2Json").click(function () {
        var rows = [];
        $('table.dynatable tbody tr').each(function (i, n) {
            var $row = $(n);
            if (n.className.toUpperCase() != "Prototype".toUpperCase() && n.className.toUpperCase() != "Header".toUpperCase()) {
                $('table.dynatable tbody td').each(function (j, d) {
                    rows.push({
                        //Here id,Name,Address,Contact are dynamic.so need to find it inside of 'th' of table.
                        //but i am not being able to find it, so i just hard coded it :(
                        Id: $row.find('td:eq(0)').text(),
                        Name: $row.find('td:eq(1)').text(),
                        Address: $row.find('td:eq(2)').text(),
                        Contact: $row.find('td:eq(2)').text()
                    });
                });
            }
        });
        //debugger;
        alert(JSON.stringify(rows));
        //alert(table.toString());
    });

TableJson

对于上表,JSON输出应为:

[{ID:"1",Name:"Bibek",Address:"lubhoo",Contact:"98411"},{ID:"4",Name:"Suraj",Address:"Sanagaun",Contact:"984511"}]

我的Html是(列和行是动态的)

<table class="dynatable">
        <thead>
            <tr class="Header">
                <th id="AddRowTh"><button class="add">Add Row</button></th>
                <th>ID &nbsp;&nbsp;<a href="#" class="RemoveColumn">Remove</a></th>
                <th>Name&nbsp;&nbsp;<a href="#" class="RemoveColumn">Remove</a></th>
                <th>Address&nbsp;&nbsp;<a href="#" class="RemoveColumn">Remove</a></th>
                <th>Contact&nbsp;&nbsp;<a href="#" class="RemoveColumn">Remove</a></th>
                <th id="AddColumnTh"><button style="width: 100px; height: 25px" class="addColumn">Add Column</button></th>
            </tr>
        </thead>
        <tbody>
            <tr class="prototype">
                <td><p class="RowName"></p><a href="#" class="RemoveRow">Remove</a><!--<button class="remove">Remove</button>--></td>
                <td><input type="text" name="id[]" value="0" class="id" /></td>
                <td><input type="text" name="name[]" value="" /></td>
                <td><input type="text" name="col4[]" value="" /></td>
                <td><input type="text" name="col3[]" value="" /></td>
            </tr>
    </table>

3 个答案:

答案 0 :(得分:4)

试试这个

$('table.dynatable tr').each(function(){
    rows.push({
        Id: $(this).find('td:eq(1) input').val(),
        Name: $(this).find('td:eq(2) input').val(),
        Address: $(this).find('td:eq(3) input').val(),
        Contact: $(this).find('td:eq(4) input').val()
    });
});

DEMO

答案 1 :(得分:2)

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

答案 2 :(得分:2)

基本解决方案 - Demo

因为您使用的是实际输入字段,所以您真正需要做的就是将其包装在表单中。将表单作为表单后,可以使用jQuery选择它并调用serializeArray()来创建输入的名称 - 值数组。

var table = $('#my_form').serializeArray();
console.log(table);
alert(JSON.stringify(table)); 

结果不会像你想要的那样100%。如您所见,所有输入都是有序的,但是没有一种真正可靠的方法来了解行之间的差异。此外,我认为订单不保证。

[{"name":"id[]","value":"1"},
 {"name":"name[]","value":"Billy"},
 {"name":"col4[]","value":"Home"},
 {"name":"col3[]","value":"Phone"},
 {"name":"id[]","value":"2"},
 {"name":"name[]","value":"Bob"},
 {"name":"col4[]","value":"work"},
 {"name":"col3[]","value":"Cell"}]

维护行分组 - Demo

如果您编辑<input name="something[]">命名数组以获得行号,那么您将能够知道哪些值属于一起。例如,如果您有两行,则输入名称将如下所示:

<tr class="prototype">
    <td><input type="text" name="id[0]" value="1" class="id" /></td>
     <td><input type="text" name="name[0]" value="Billy" /></td>
     <td><input type="text" name="col4[0]" value="Home" /></td>
     <td><input type="text" name="col3[0]" value="Phone" /></td>
 </tr>
 <tr class="prototype">
     <td><input type="text" name="id[1]" value="2" class="id" /></td>
     <td><input type="text" name="name[1]" value="Bob" /></td>
     <td><input type="text" name="col4[1]" value="work" /></td>
     <td><input type="text" name="col3[1]" value="Cell" /></td>
 </tr>

(注意名称数组中有行号),返回的结果如下所示:

[{"name":"id[0]","value":"1"},
 {"name":"name[0]","value":"Billy"},
 {"name":"col4[0]","value":"Home"},
 {"name":"col3[0]","value":"Phone"},
 {"name":"id[1]","value":"2"},
 {"name":"name[1]","value":"Bob"},
 {"name":"col4[1]","value":"work"},
 {"name":"col3[1]","value":"Cell"}]

将结果按到所需的输出 - Demo

显然结果仍然与您所寻找的不符,但也可以修复。我们知道该字段的名称,我们知道该字段的值,现在我们也知道它的行号。使用一些正则表达式,我们可以从行号中分离出名称。使用循环我们可以将事物移动到我们喜欢的格式:

var table = $('#my_form').serializeArray();
var final_results = [];
var row_patt = /\[(\d+)\]$/; // Gets the row number inside []
var name_patt = /^[^\[]+/; // Gets the name without the [0]
$(table).each( function(index, ele){
    // Get the name of input and row number
    var rowNum = parseInt(row_patt.exec(ele.name)[1]);
    var name = name_patt.exec(ele.name);

    // Add the name and value to the correct spot in results
    if( final_results[rowNum] === undefined ){
        final_results[rowNum] = {};
    }
    final_results[rowNum][name] = ele.value;
});

现在我们有一个格式很好的哈希数组,每行列出每个值:

[{"id":"1","name":"Billy","col4":"Home","col3":"Phone"},
 {"id":"2","name":"Bob",  "col4":"work","col3":"Cell"}]