cnavliz cnavliz - 1 month ago 20
HTML Question

Convert table HTML to JSON

I have this:

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


And I need a json format.

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


I've tried with https://github.com/lightswitch05/table-to-json but it doesn't work for the headings in every row :(

EDIT: http://jsfiddle.net/Crw2C/773/

Answer

Assuming all you need is to get the first/second cells of each row as key/value pairs, you can use .reduce() to iterate of the rows and just grab the text content of .cells[0] and .cells[1] to use as each key/value pair:

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>

The Array.prototype.reduce method takes a collection and uses an accumulator to reduce it down to whatever state you want. Here we just reduce it to an object, so we pass one in after the callback.

For every row, we use the first cell's content as the object key, and the second cell's content as the value. We then return the object from the callback so that it's given back to us in the next iteration.

Finally, .reduce() returns the last thing we returned (which of course is the object we started with), and that's your result.