将表 HTML 转换为 JSON

Convert table HTML to JSON

本文关键字:JSON 转换 HTML 将表      更新时间:2023-09-26

>我有这个:

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

我需要一个 JSON 格式。

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

我已经尝试过 https://github.com/lightswitch05/table-to-json 但它不适用于每一行中的标题:(

编辑:http://jsfiddle.net/Crw2C/773/

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

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

然而,这是一个临时解决办法,因此需要一些工作来适应更一般的情况。不过,它显示了这个概念。

请注意,不能保证对象属性的返回顺序与它们在表中出现的顺序相同,您可能会得到{"Age:":"22","Name:":"Carlos"}

假设您所需要的只是将每行的第一个/第二个单元格作为键/值对,您可以使用.reduce()来迭代行,只需获取.cells[0]的文本内容和.cells[1]作为每个键/值对:

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);
<table>
    <tr>
        <th>Name:</th>
        <td>Carlos</td>
    </tr>        
    <tr>
        <th>Age:</th>
        <td>22</td>
    </tr>
</table>
<pre></pre>

Array.prototype.reduce 方法采用集合并使用累加器将其降低到所需的任何状态。在这里,我们只是将其简化为一个对象,因此我们在回调后传递一个对象。

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

最后,.reduce()返回我们返回的最后一件事(当然是我们开始的对象),这就是你的结果。

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);
<table>
    <tr>
        <th>Name:</th>
        <td>Carlos</td>
    </tr>        
    <tr>
        <th>Age:</th>
        <td>22</td>
    </tr>
</table>
<pre></pre>

您使用的

表到 JSON 库在表中需要不同的格式。

它期望一个表,所有标题都在第一行,然后是后续行中的数据。

换句话说,它希望你的表是这样的结构

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

这是你的JSFiddle的分支版本,它在其中工作。