Aakash Takale
Aakash Takale

Reputation: 115

Convert HTML table data to JSON using javascript/jquery

My table rows are being dynamically generated when I click "+" button. When I populate the fields and click submit button (next to "+") my JSON gets displayed to the console as shown in the image below.

HTMLtoJSON

When I generate JSON, I want to exclude the row which is unfilled (In this case 3rd row). Also, I want exclude column 1 (which consists of 3 buttons).

As we can see the JSON data is consisting lots of "\n" and \t" which is annoying.

I wrote following code by referring to some of the Stack Overflow pages.

function createJSON(){

 var myJSON = { Key: [] };

 var headers = $('table th');
 $('table tbody tr').each(function(i, tr){
   var obj = {}, 

   $tds = $(tr).find('td');

   headers.each(function(index, headers){
     obj[$(headers).text()] = $tds.eq(index).text();
   });

   myJSON.Key.push(obj);
 });

 console.log(JSON.stringify(myJSON));

}

Upvotes: 1

Views: 1311

Answers (1)

Barmar
Barmar

Reputation: 780673

The rows that aren't filled have <input> elements. You can use a selector that excludes them.

$('table tbody tr:not(:has(input))').each(...)

You can get rid of all the newline and other whitespace characters around the headings with .trim():

headers.each(function(index, headers){
    obj[$(headers).text().trim()] = $tds.eq(index).text();
});

To skip the first column, you can use :gt(0) in the selectors:

var headers = $('table th:gt(0)');
var $tds = $(tr).find('td:gt(0)');

Upvotes: 2

Related Questions