victorio
victorio

Reputation: 6676

how to convert/transform an HTML table tbody (with rowspans) TO json?

I have an HTML table with combined row td's, or how to say, I don't know how to express myself (I am not so good at English), so I show it! This is my table:

<table border="1">
    <thead>
        <tr>
            <th>line</th>
            <th>value1</th>
            <th>value2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td rowspan="2">1</td>
            <td>1.1</td>
            <td>1.2</td>
        </tr>
        <tr>
            <td>1.3</td>
            <td>1.4</td>
        </tr>
        <tr>
            <td rowspan="2">2</td>
            <td>2.1</td>
            <td>2.2</td>
        </tr>
        <tr>
            <td>2.3</td>
            <td>2.4</td>
        </tr>
    </tbody>
</table>

(you can check it here)

I want to convert this table to a JSON variable by jquery or javascript. How should it look like, and how should I do it? Thank you, if you can help me!

Upvotes: 1

Views: 2382

Answers (3)

B.F.
B.F.

Reputation: 477

To make a somehow representation of your table made no problem to me, but the problem is how to parse it back to HTML! Here a JSON with the first 6 tags:

{"table":{"border":1,"thead":{"th":{"textContent":"line","tr":"textContent":"value1",...}}}}}...

OR for better understanding:

{"tag":"table","border":1,"child":{"tag":"thead","child":{"tag":"th","textContent":"line",
   "child":{"tag":"tr","textContent":"value1","child":...}}}}...

Closing tags are included.

For further explanations I need to know whether your table is a string or part of the DOM.

Upvotes: 1

lashab
lashab

Reputation: 186

if you want to convert only text use this one :

var array = [];

$('table').find('thead tr').each(function(){
    $(this).children('th').each(function(){
      array.push($(this).text());
    })
}).end().find('tbody tr').each(function(){
    $(this).children('td').each(function(){
      array.push($(this).text());
    }) 
})

var json = JSON.stringify(array);

Upvotes: 1

user1386320
user1386320

Reputation:

I belive this is what you want:

var jsonTable = {};

// add a new array property named: "columns"
$('table').find('thead tr').each(function() {
    jsonTable.columns = $(this).find('th').text();
};

// now add a new array property which contains your rows: "rows"
$('table').find('tbody tr').each(function() {
    var row = {};

    // add data by colum names derived from "tbody"

    for(var i = 0; i < jsonTable.columnsl.length; i++) {
        row[ col ] = $(this).find('td').eq( i ).text();
    }

    // push it all to the results..

    jsonTable.rows.push( row );
};

alert(JSON.stringify(jsonTable));

I think there should be some corrections, but this is it I think.

Upvotes: 0

Related Questions