0

I have following type of table, which is dynamically generated. I want this to convert it into JSON in following format. I have tried various methods, but in vain.

Could some one please help me informing how I can generate this using jQuery.

Note: inner tables are dynamically generated using for loop.

Expected JSON format:

{"array" : [{"header1":"table1data1","header2":"table1data2","header3":"table1data3" },
            {"header1":"table2data1","header2":"table2data2","header3":"table2data3" },
            {"header1":"table3data1","header2":"table3data2","header3":"table3data3" }  
          ]} 

Table:

<table id="Maintable">
<tr>
<td>

    <table id="headertable">
         <tr><th> header1</th></tr>
         <tr><th> headr2</th></tr>
         <tr><th> header3</th></tr> 
    </table>


</td>
<td>
    <table class="innertable"  id="innertable1">
         <tr><td> table1data1</td></tr>
         <tr><td> table1data2</td></tr>
         <tr><td> table1data3</td></tr> 
    </table>

</td>
<td>
    <table class="innertable"  id="innertable2">
         <tr><td> table2data1</td></tr>
         <tr><td> table2data2</td></tr>
         <tr><td> table2data3</td></tr> 
    </table>

</td>

...

<td>
    <table class="innertable" id="innertable10">
         <tr><td> table10data1</td></tr>
         <tr><td> table10data2</td></tr>
         <tr><td> table10data3</td></tr> 
    </table>

</td>

</tr>
</table>
user692146
  • 41
  • 1
  • 9

2 Answers2

1

After some google and self hit and trail, I got the answer:

     //logic for creating json from html table
      var myRows = [];
      var $headers = $("th");

      var $tbody = $(".innertable tbody").each(function(index) {

      $rows = $(this).find("tr:not(:last-child)");// I have some delete buttons in the last td of each column which i dont want so not(:last-child)
      myRows[index] = {};
      $rows.each(function(rowIndex) {
      myRows[index][$($headers[rowIndex]).html()] = $(this).text();
     });    
  });

    var myObj = {};
    myObj.array= myRows;
    //alert(JSON.stringify(myObj));

refrence:How to convert the following table to JSON with javascript?

Community
  • 1
  • 1
user692146
  • 41
  • 1
  • 9
0

There is a library which converts table to json format: https://github.com/lightswitch05/table-to-json

i hope it helps.

maverickosama92
  • 2,685
  • 2
  • 21
  • 35
  • Thanks for the link. But I want something which reads data coulmn wise and not row wise. i guess this plugin reading row wise. And also I have inner tables which this plugin doesnot read. – user692146 Aug 06 '13 at 06:37