将表格HTML转换为JSON

时间:2015-06-17 02:23:38

标签: javascript html json html-table

我有这个:

<table>
    <tr>
        <th>Name:</th>
        <td>Carlos</td>
    </tr>        
    <tr>
        <th>Age:</th>
        <td>22</td>
    </tr>
</table>

我需要一种JSON格式。

{"Name":"Carlos","Age": 22}

我已尝试使用https://www.eclipse.org/jetty/documentation/current/embedded-examples.html#embedded-one-webapp,但它并不适用于每一行的标题:(

编辑:https://github.com/lightswitch05/table-to-json

4 个答案:

答案 0 :(得分:4)

假设您需要的是将每行的第一个/第二个单元格作为键/值对,您可以使用.navlink li a:before { content:'1'; } 迭代行,只需抓取.reduce()的文本内容即可.cells[0]用作每个键/值对:

&#13;
&#13;
.cells[1]
&#13;
var t = document.querySelector("table");

var j = [].reduce.call(t.rows, function(res, row) {
    res[row.cells[0].textContent.slice(0,-1)] = row.cells[1].textContent;
    return res
}, {});

document.querySelector("pre").textContent = JSON.stringify(j, null, 2);
&#13;
&#13;
&#13;

<table> <tr> <th>Name:</th> <td>Carlos</td> </tr> <tr> <th>Age:</th> <td>22</td> </tr> </table> <pre></pre>方法接受一个集合并使用累加器将其缩减到您想要的任何状态。这里我们只是将它缩减为一个对象,所以我们在回调后传入一个。

对于每一行,我们使用第一个单元格的内容作为对象键,并使用第二个单元格的内容作为值。然后我们从回调中返回对象,以便在下一次迭代中将它返回给我们。

最后,Array.prototype.reduce会返回我们返回的最后一件事(当然是我们开始使用的对象),这是您的结果。

答案 1 :(得分:2)

您可以将OP中的表格转换为所需格式,方法是先将其转换为Object,然后使用JSON.stringify获取所需的字符串:

var _ref;

if ((_ref = c.urls.voice) != null) {
  _ref;
} else {
  "";
};

但是,这是一个 ad hoc 解决方案,因此需要一些工作来适应更一般的情况。它显示了这个概念。

请注意,无法保证对象属性的返回顺序与表中显示的顺序相同,您可能会获得<table id="t0"> <tr> <th>Name:</th> <td>Carlos</td> </tr> <tr> <th>Age:</th> <td>22</td> </tr> </table> <script> function tableToJSON(table) { var obj = {}; var row, rows = table.rows; for (var i=0, iLen=rows.length; i<iLen; i++) { row = rows[i]; obj[row.cells[0].textContent] = row.cells[1].textContent } return JSON.stringify(obj); } console.log(tableToJSON(document.getElementById('t0'))); // {"Name:":"Carlos","Age:":"22"}" </script>

答案 2 :(得分:0)

&#13;
&#13;
var t = document.querySelector("table");

var j = [].reduce.call(t.rows, function(res, row) {
    res[row.cells[0].textContent.slice(0,-1)] = row.cells[1].textContent;
    return res
}, {});

document.querySelector("pre").textContent = JSON.stringify(j);
&#13;
<table>
    <tr>
        <th>Name:</th>
        <td>Carlos</td>
    </tr>        
    <tr>
        <th>Age:</th>
        <td>22</td>
    </tr>
</table>
<pre></pre>
&#13;
&#13;
&#13;

答案 3 :(得分:-1)

您正在使用的Table-to-JSON library期望表格中的格式不同。

期望第一行中包含所有标题的表,后面是后续行中的数据。

换句话说,它希望你的表格结构如下

<table>
    <tr>
        <th>Name</th>
        <th>Age</th>
    </tr>        
    <tr>
        <td>Carlos</td>
        <td>22</td>
    </tr>
</table>

这是a forked version of your JSFiddle,其中有效。

相关问题