Skip to content Skip to sidebar Skip to footer

How To Convert Data Table To Json In Javascript

I want to convert data table to Json. I use node.js I have Data Table as : ------------------------------------- | Month | Name | Sum | -------------------------

Solution 1:

Here you go with a solution https://jsfiddle.net/mou882tw/

var data = [];
var lastMonth = "";

var child = document.getElementsByTagName('tr');
var temp = {};
var th = child[0].children;
for(var i=1; i<child.length; i++){
  var td = child[i].children;
  if(lastMonth != td[0].textContent){
  	if( JSON.stringify(temp) != '{}')
  		data.push(temp);
  	temp = {};
  	temp["Information"] = [];
  }

  var innerJSON = {};
  for(var j=0; j<td.length; j++){
  	if(j == 0){
    	temp[th[j].textContent] = td[j].textContent;
      lastMonth = td[j].textContent;
    } else {
    	innerJSON[th[j].textContent] = td[j].textContent;
    }
  }
  temp["Information"].push(innerJSON);
  if(i == (child.length -1)){
  	data.push(temp);
  }
}
console.log(data);
<table><thead><tr><th>Month</th><th>Name</th><th>Sum</th></tr></thead><tbody><tr><td>January</td><td>John</td><td>25</td></tr><tr><td>February</td><td>Jane</td><td>30</td></tr><tr><td>February</td><td>John</td><td>35</td></tr><tr><td>February</td><td>Alex</td><td>20</td></tr><tr><td>March</td><td>Jane</td><td>32</td></tr><tr><td>March</td><td>John</td><td>35</td></tr><tr><td>March</td><td>Alex</td><td>30</td></tr></tbody></table>

Hope this will help you.

Solution 2:

Any possibility of table to json but with nested json. How it will be formated

Post a Comment for "How To Convert Data Table To Json In Javascript"