Html表到json数组 [英] Html table to array of json

查看:151
本文介绍了Html表到json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have table with dynamic Rows and columns,i was trying to convert HTML table to Json by looping through each tr and td and finding values inside textbox but with no luck.Here is my js code.

 $("#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());
    });

对于上表,JSON输出应为:

For above table JSON output should be:

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

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

My Html is (columns and rows are dynamic)

<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>


推荐答案

基本解决方案 - 演示



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

Basic Solution - Demo

Because you are using actual input fields, all you really need to do is wrap it in a form. Once you have it as a form, you can select it using jQuery and call serializeArray() to create a name-value array of your inputs.

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

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

The result isn't going to be 100% like you want it. As you can see, all the inputs are in order, but there isn't a really reliable way to know the difference between the rows. Also, I don't think order is guaranteed.

[{"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"}]






维护行分组 - 演示



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


Maintain row groupings - Demo

If you edit your <input name="something[]"> named arrays to have the row number, then you'll be able to know which values belong together. For example, if you had two rows, the input names would look like this:

<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>

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

(notice the name arrays have the row number in it) and the returning results would looks like this:

[{"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"}]






将结果按到所需的输出 - 演示



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


Massage results into desired output - Demo

Obviously the results still don't match what you are looking for, but that can be fixed too. We know the name of the field, we know the field's value, and now we know its row number too. Using some regular expressions, we can separate out the name from the row number. Using a loop we can move things around to a format that we like:

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

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

Now we have a nicely formatted array of hashes that list each value per row:

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

这篇关于Html表到json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆