Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 951
cnavarreteliz Avatar asked Sep 15 '25 11:09

cnavarreteliz


2 Answers

You can convert the table in the OP to the required format by first converting it to an Object, then using JSON.stringify to get the required string:

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

However, that is an ad hoc solution, so will need some work to be adapted to a more general case. It shows the concept though.

Note that there is no guarantee that the object properties will be returned in the same order as they appear in the table, you may get {"Age:":"22","Name:":"Carlos"}.

like image 74
RobG Avatar answered Sep 18 '25 10:09

RobG


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.

like image 43
2 revsuser1106925 Avatar answered Sep 18 '25 09:09

2 revsuser1106925