简体   繁体   English

将带有 select 的 html 表转换为 Json

[英]convert a html table with select to Json

I have difficulties to properly export to a JSON table the content of a html table when it contains a select tag.当包含 select 标记时,我很难将 html 表的内容正确导出到 JSON 表。 I need the selected option value to be exported, not the full content of the select inputbox (ex: "Animal":"Dog\n Cat\n Hamster\n Parrot\n Spider\n Goldfish" should be "Animal":"Cat")我需要导出选定的选项值,而不是 select 输入框的全部内容(例如:“动物”:“狗\n 猫\n 仓鼠\n 鹦鹉\n 蜘蛛\n 金鱼”应该是“动物”:“猫”)

The html code I use is:我使用的 html 代码是:

<html>
<body>
  <table id="students" border="1">
    <thead>
      <tr>
        <th>Name</th>
         <th> Animal </th>
        <th>Age</th>
        <th>Grade</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Oscar</td>
             <td>  <select name="pets" id="pet-select">

    <option value="dog">Dog</option>
    <option value="cat" selected>Cat</option>
    <option value="hamster">Hamster</option>
</select>
 </td>
        <td>23</td>
        <td>16.5</td>
      </tr>
      <tr>
        <td>Antonio</td>
        <td>  <select name="pets" id="pet-select">

    <option value="dog">Dog</option>
    <option value="cat">Cat</option>
    <option value="hamster" selected>Hamster</option>
  
</select>
 </td>
        <td>32</td>
        <td>14</td>
      </tr>
      <tr>
        <td>Jessica</td>
             <td>  <select name="pets" id="pet-select">

    <option value="dog" selected >Dog</option>
    <option value="cat">Cat</option>
    <option value="hamster">Hamster</option>
  
</select>
 </td>
        <td>21</td>
        <td>19</td>
      </tr>
    </tbody>
  </table>
  <br>
  <button id="run">Convert!</button>
</body>
</html>

and the JS:和JS:

/*! tabletojson - v0.11.1 - Daniel White */ ! function(a) {
    "use strict";
    a.fn.tableToJSON = function(b) {
        var c = {
            ignoreColumns: [],
            onlyColumns: null,
            ignoreHiddenRows: !0,
            ignoreEmptyRows: !1,
            headings: null,
            allowHTML: !1,
            includeRowId: !1,
            textDataOverride: "data-override",
            textExtractor: null
        };
        b = a.extend(c, b);
        var d = function(a) {
                return void 0 !== a && null !== a
            },
            e = function(c) {
                return d(b.onlyColumns) ? -1 === a.inArray(c, b.onlyColumns) : -1 !== a.inArray(c, b.ignoreColumns)
            },
            f = function(b, c) {
                var e = {},
                    f = 0;
                return a.each(c, function(a, c) {
                    f < b.length && d(c) && (e[b[f]] = c, f++)
                }), e
            },
            g = function(c, d, e) {
                var f = a(d),
                    g = b.textExtractor,
                    h = f.attr(b.textDataOverride);
                return null === g || e ? a.trim(h || (b.allowHTML ? f.html() : d.textContent || f.text()) || "") : a.isFunction(g) ? a.trim(h || g(c, f)) : "object" == typeof g && a.isFunction(g[c]) ? a.trim(h || g[c](c, f)) : a.trim(h || (b.allowHTML ? f.html() : d.textContent || f.text()) || "")
            },
            h = function(c, d) {
                var e = [],
                    f = b.includeRowId,
                    h = "boolean" == typeof f ? f : "string" == typeof f ? !0 : !1,
                    i = "string" == typeof f == !0 ? f : "rowId";
                return h && "undefined" == typeof a(c).attr("id") && e.push(i), a(c).children("td,th").each(function(a, b) {
                    e.push(g(a, b, d))
                }), e
            },
            i = function(a) {
                var c = a.find("tr:first").first();
                return d(b.headings) ? b.headings : h(c, !0)
            },
            j = function(c, h) {
                var i, j, k, l, m, n, o, p = [],
                    q = 0,
                    r = [];
                return c.children("tbody,*").children("tr").each(function(c, e) {
                    if (c > 0 || d(b.headings)) {
                        var f = b.includeRowId,
                            h = "boolean" == typeof f ? f : "string" == typeof f ? !0 : !1;
                        n = a(e);
                        var r = n.find("td").length === n.find("td:empty").length ? !0 : !1;
                        !n.is(":visible") && b.ignoreHiddenRows || r && b.ignoreEmptyRows || n.data("ignore") && "false" !== n.data("ignore") || (q = 0, p[c] || (p[c] = []), h && (q += 1, "undefined" != typeof n.attr("id") ? p[c].push(n.attr("id")) : p[c].push("")), n.children().each(function() {
                            for (o = a(this); p[c][q];) q++;
                            if (o.filter("[rowspan]").length)
                                for (k = parseInt(o.attr("rowspan"), 10) - 1, m = g(q, o), i = 1; k >= i; i++) p[c + i] || (p[c + i] = []), p[c + i][q] = m;
                            if (o.filter("[colspan]").length)
                                for (k = parseInt(o.attr("colspan"), 10) - 1, m = g(q, o), i = 1; k >= i; i++)
                                    if (o.filter("[rowspan]").length)
                                        for (l = parseInt(o.attr("rowspan"), 10), j = 0; l > j; j++) p[c + j][q + i] = m;
                                    else p[c][q + i] = m;
                            m = p[c][q] || g(q, o), d(m) && (p[c][q] = m), q++
                        }))
                    }
                }), a.each(p, function(c, g) {
                    if (d(g)) {
                        var i = d(b.onlyColumns) || b.ignoreColumns.length ? a.grep(g, function(a, b) {
                                return !e(b)
                            }) : g,
                            j = d(b.headings) ? h : a.grep(h, function(a, b) {
                                return !e(b)
                            });
                        m = f(j, i), r[r.length] = m
                    }
                }), r
            },
            k = i(this);
        return j(this, k)
    }
}(jQuery);

// Code goes here

$('#run').click(function() {
    var table = $('#students').tableToJSON({
        extractor: function($index, $cell) {
            return {
                name: $cell.find('td').value
            };
        }
    });
    alert(JSON.stringify(table));
});

you can check the result in the following codepen您可以在以下代码笔中检查结果

One way is use the index in the extractor.一种方法是使用提取器中的索引。 When index is one return the value of the select, otherwise return the cell text当 index 为 1 时返回 select 的值,否则返回单元格文本

 $('#run').click(function() { var table = $('#students').tableToJSON({ extractor: function($index, $cell) { if ($index == 1) { return $cell.find('select').val() } return $cell.text() } }); console.log(JSON.stringify(table)); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/table-to-json@1.0.0/lib/jquery.tabletojson.min.js" integrity="sha256-H8xrCe0tZFi/C2CgxkmiGksqVaxhW0PFcUKZJZo1yNU=" crossorigin="anonymous"></script> <table id="students" border="1"> <thead> <tr> <th>Name</th> <th> Animal </th> <th>Age</th> <th>Grade</th> </tr> </thead> <tbody> <tr> <td>Oscar</td> <td> <select name="pets" id="pet-select"> <option value="dog">Dog</option> <option value="cat" selected>Cat</option> <option value="hamster">Hamster</option> </select> </td> <td>23</td> <td>16.5</td> </tr> <tr> <td>Antonio</td> <td> <select name="pets" id="pet-select"> <option value="dog">Dog</option> <option value="cat">Cat</option> <option value="hamster" selected>Hamster</option> </select> </td> <td>32</td> <td>14</td> </tr> <tr> <td>Jessica</td> <td> <select name="pets" id="pet-select"> <option value="dog" selected>Dog</option> <option value="cat">Cat</option> <option value="hamster">Hamster</option> </select> </td> <td>21</td> <td>19</td> </tr> </tbody> </table> <br> <button id="run">Convert!</button>

I think your issue is that for a <select> , you need to get the selected option .我认为您的问题是对于<select> ,您需要获取selected option Otherwise it will return all option values as you've described.否则,它将返回您所描述的所有选项值。 Unless you absolutely need to use .tableToJSON() , which looks like alot of obfuscated overhead, I simplified the code into something a little more easier to follow.除非您绝对需要使用.tableToJSON() ,这看起来有很多混淆的开销,否则我将代码简化为更容易理解的东西。 Also this is more flexible than the current accepted answer in that you could move the select to another column and it will still work.这也比当前接受的答案更灵活,因为您可以将 select 移动到另一列,它仍然可以工作。

 $('#run').on('click', function() { let items = $('thead th').get().map(th => th.textContent.trim()), json = []; $('tbody tr').each(function(row, tr) { json[row] = {}; $(tr).find('td').each(function(index, td) { json[row][items[index]] = td.firstElementChild? td.firstElementChild.selectedOptions[0].value: td.textContent; }); }); console.log(JSON.stringify(json)); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <html> <body> <table id="students" border="1"> <thead> <tr> <th>Name</th> <th> Animal </th> <th>Age</th> <th>Grade</th> </tr> </thead> <tbody> <tr> <td>Oscar</td> <td> <select name="pets" id="pet-select"> <option value="dog">Dog</option> <option value="cat" selected>Cat</option> <option value="hamster">Hamster</option> </select> </td> <td>23</td> <td>16.5</td> </tr> <tr> <td>Antonio</td> <td> <select name="pets" id="pet-select"> <option value="dog">Dog</option> <option value="cat">Cat</option> <option value="hamster" selected>Hamster</option> </select> </td> <td>32</td> <td>14</td> </tr> <tr> <td>Jessica</td> <td> <select name="pets" id="pet-select"> <option value="dog" selected >Dog</option> <option value="cat">Cat</option> <option value="hamster">Hamster</option> </select> </td> <td>21</td> <td>19</td> </tr> </tbody> </table> <br> <button id="run">Convert!</button> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM