1

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

}

1 Answer 1

2

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)');
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Barmar, that worked but how do I skip the column 1? JSON still looks like this {"Key":[{"":"","Field Name":"a","Field Type":"Text","Special Field Subtype":"USD","Description":"f"}]}
@AakashTakale USe :gt(0) in the selectors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.