Get Table data in json format - javascript

Hello everyone I'm trying to get table data in json format here is my table
<table>
<thead>
<tr>
<th>srno</th>
<th>name</th>
<th>email</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Jhon One</td>
<td>Doe one</td>
</tr>
<tr>
<td>2</td>
<td>Jhon two</td>
<td>Doe Two</td>
</tr>
</tbody>
</table>
<button>
convert
</button>
the result which i am getting is this
{
"0": {
"1",
"Jhon One",
"Doe one"
}
,
"1": {
"2",
"Jhon two",
"Doe Two"
}
}
using the below javascript
$("button").click(function() {
var json = html2json();
alert(json);
});
function html2json() {
var json = '{';
var otArr = [];
// var i = 1;
var tbl2 = $('table tbody tr').each(function(e) {
x = $(this).children();
var itArr = [];
x.each(function() {
itArr.push('"' + $(this).text() + '"');
});
otArr.push('"' + e + '": {' + itArr.join(',') + '}');
})
json += otArr.join(",") + '}'
return json;
}
but i want to add key to every value and the number should start from one and not zero.
i have a set of desire result and it should look like this
any help is appreciated
{
"1": {
no: "1",
name:"Jhon One",
lastname "Doe one"
}
,
"2": {
no: "1",
name:"Jhon two",
lastname "Doe two"
}
}
here is the fiddel link which i have tried
https://jsfiddle.net/k228n2bn/

Just change the following line
otArr.push('"' + e + '": {' + itArr.join(',') + '}');
to
otArr.push('"' + (e+1) + '": {' + itArr.join(',') + '}');
The parenthesis will add the values as numbers not strings.
Also, add keys array for internal object keys.
function html2json() {
var json = '{';
var otArr = [];
// var i = 1;
var tbl2 = $('table tbody tr').each(function(e) {
x = $(this).children();
var itArr = [];
var keys = ['no','name','lastname'];
x.each(function(i) {
itArr.push('"' + keys[i] + '":"' + $(this).text() + '"');
});
otArr.push('"' + (e+1) + '": {' + itArr.join(',') + '}');
})
json += otArr.join(",") + '}'
return json;
}

You can convert e to a Number and add one to it like in this fiddle.
function html2json() {
var json = '{';
var otArr = [];
// var i = 1;
var tbl2 = $('table tbody tr').each(function(e) {
x = $(this).children();
var itArr = [];
x.each(function() {
itArr.push('"' + $(this).text() + '"');
});
otArr.push('"' + (Number(e) + 1) + '": {' + itArr.join(',') + '}');
})
json += otArr.join(",") + '}'
return json;
}
The json you're returning is not valid though. You may want to do something like this fiddle if you can to simplify and ensure valid json and to create your objects from any table structure.
function html2json() {
var otArr = [];
var tblHeaders = Array.from($('table thead tr')
.children())
.map(header => $(header).text());
var tbl2 = $('table tbody tr').each(function(e) {
const values = Array.from($(this).children());
const row = {};
for (let i = 0; i < tblHeaders.length; i++){
row[tblHeaders[i]] = $(values[i]).text();
}
otArr.push({
[e+1]: row
})
})
json = JSON.stringify(otArr);
return json;
}

Try e+1
change otArr.push('"' + e + '": {' + itArr.join(',') + '}');
to
otArr.push('"' + (e+1) + '": {' + itArr.join(',') + '}');
$("button").click(function() {
var json = html2json();
});
function html2json() {
var json = '{';
var otArr = [];
var tbl2 = $('table tbody tr').each(function(e) {
x = $(this).children();
var itArr = [];
x.each(function(e) {
var items='';
if(e == 0){
items +='no : "'+ $(this).text()+'"';
}
if(e == 1){
items +='name : "' +$(this).text()+'"';
}
if(e == 2){
items +='email : "' +$(this).text()+'"';
}
itArr.push(items);
});
otArr.push('"' + (e+1) + '": {' + itArr.join(',') + '}');
})
json += otArr.join(",") + '}'
alert(json);
return json;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>srno</th>
<th>name</th>
<th>email</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Jhon One</td>
<td>Doe one</td>
</tr>
<tr>
<td>2</td>
<td>Jhon two</td>
<td>Doe Two</td>
</tr>
</tbody>
</table>
<button>
convert
</button>

Maybe you can use theads as keys for the generated objects.
Check this jsfiddle.
function html2json() {
var $table = $('table');
var $ths = $table.find('thead>tr>th');
var rows = {};
$table.find('tbody>tr').each(function () {
var row = {};
$(this).children().each(function (index) {
row[$ths[index].textContent] = this.textContent;
});
rows[row.srno] = row;
});
return JSON.stringify(rows);
}

Related

How to rebuild a table from a json?

The following is almost working:
var data = [{"Mamma":["Papa","Nonna"],"Hello":["Bye","Yes"]}];
var colHeader = Object.keys(data[0]);
for(var i=0; i<colHeader.length; i++) {
$('table thead tr').append('<td>' + colHeader[i] + '</td>');
}
for(var i=0; i<data.length; i++){
$('table tbody').append('<tr></tr>')
for(var j= 0; j<colHeader.length; j++){
$('table tbody tr').last().append('<td>' + data[i][colHeader[j]] + '</td>');
}
}
But i get the table with two values in a td as per the image below
Here it is a jsFIddle
You will need to also loop object values which are arrays and append then by index.
var data = [{"Mamma": ["Papa", "Nonna"],"Hello": ["Bye", "Yes"]}];
data.forEach(obj => {
Object.keys(obj).forEach(key => {
$('thead').append($('<th>').text(key));
obj[key].forEach((e, i) => {
if(!$("tbody tr:eq("+i+")").length) $("<tr>").appendTo($("tbody"));
$("tbody tr:eq(" + i + ")").append($('<td>').text(e))
})
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead></thead>
<tbody></tbody>
</table>
Please try it with the sample in this snippet and let me know if it is the expected output.
var data = [{"Hello": ["Bye", "", "", "", "", ""],"h2": ["", "", "", "c", "", "d"]}];
var outerIndex = 0;
$.each(data[0],(key, arr) => {
$('thead').append($('<th>').text(key));
data[0][key].forEach((e, i) => {
if(!$("tbody tr:eq("+i+")").length)
$("<tr>").appendTo($("tbody"));
var colIndex = $("tbody tr:eq(" + i + ")").children('td').length;
while(colIndex++ !== outerIndex){
$("tbody tr:eq(" + i + ")").append('<td>');
}
$("tbody tr:eq(" + i + ")").append($('<td>').text(e))
})
outerIndex++
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead></thead>
<tbody></tbody>
</table>

Possible to only run code block inside for loop once?

I'm using the loop to find whole table columns containing cells with a certain class and it works fine for applying class and the other stuff below. The only problem is that I would also like to output the value of the cells once. Is this possible somehow?
$('td:first-child').each(function() {
for (var i = 0; i <= 5; i++) {
var col = $('.tabell tr').find('td:nth-child(' + i + ').check').length;
if (col == 5) {
$(".bingocl").fadeIn(2000);
var column = $('.tabell tr').find('td:nth-child(' + i + ')');
column.addClass("bingo", 2000);
var text = column.text().toUpperCase();
$("#textout").append(text + "!!");
}
}
});
Update:
$('td:first-child').each(function() {
for(var i = 0; i <= 5; i++) {
var col = $('.tabell tr').find('td:nth-child(' + i + ').check').length;
var column = $('.tabell tr').find('td:nth-child(' + i + ')');
if (col == 5) {
$( ".bingocl" ).fadeIn(2000);
column.addClass("bingo", 2000);
column.each(function() {
$("#textout").append($(this).html() + " ");
});
break;
}
}
});
function in it's entirety:
var main = function() {
//Styling the rows
$(".tabell tbody").find("tr").each(function(idx) {
var row = $(this);
if (row.find("td").length == row.find("td.check").length) {
row.addClass("bingo");
$(".bingocl").fadeIn(2000);
var text = row.find("td").text().toUpperCase();
$("#textout").append(text + "!!");
}
});
//styling cols
$('td:first-child').each(function() {
for (var i = 0; i <= 5; i++) {
var col = $('.tabell tr').find('td:nth-child(' + i + ').check').length;
if (col == 5) {
$(".bingocl").fadeIn(2000);
var column = $('.tabell tr').find('td:nth-child(' + i + ')');
column.addClass("bingo", 2000);
var text = column.text().toUpperCase();
$("#textout").append(text + "!!");
break;
}
}
});
}
$(document).ready(main);
Provided you already have access to your winning row/column (you add a bingo class to them), you can access each individual element to output it's value.
Your code becomes:
var main = function() {
//Styling the rows
$(".tabell tbody").find("tr").each(function(idx) {
var row = $(this);
if (row.find("td").length == row.find("td.check").length) {
row.addClass("bingo");
$(".bingocl").fadeIn(2000);
// Iterate your row elements
row.each(function(){document.write($(this).html() + " ");});
}
});
//styling cols
//$('td:first-child').each(function() { <- remove this
for (var i = 0; i <= 5; i++) {
var col = $('.tabell tr').find('td:nth-child(' + i + ').check').length;
if (col == 5) {
$(".bingocl").fadeIn(2000);
var column = $('.tabell tr').find('td:nth-child(' + i + ')');
column.addClass("bingo", 2000);
// Iterate your column elements
column.each(function(){document.write($(this).html() + " ");});
break;
}
}
//}); <- remove this
}
$(document).ready(main);
Live example
var column = $(".selected_column");
var row = $(".selected_row");
column.addClass("bingo");
row.addClass("bingo");
column.each(function() {
$("#textout").append($(this).html() + " ");
});
row.each(function() {
$("#textout").append($(this).html() + " ");
});
.selected_column {
background: blue;
}
.selected_row {
background: yellow;
}
.selected_column.selected_row {
background: green;
}
.bingo {
border: 2px solid lime;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>A</td>
<td class="selected_column">B</td>
<td>C</td>
<td>D</td>
<td>E</td>
</tr>
<tr>
<td>F</td>
<td class="selected_column">G</td>
<td>H</td>
<td>I</td>
<td>J</td>
</tr>
<tr>
<td>K</td>
<td class="selected_column">L</td>
<td>M</td>
<td>N</td>
<td>O</td>
</tr>
<tr>
<td class="selected_row">P</td>
<td class="selected_column selected_row">Q</td>
<td class="selected_row">R</td>
<td class="selected_row">S</td>
<td class="selected_row">T</td>
</tr>
<tr>
<td>U</td>
<td class="selected_column">V</td>
<td>W</td>
<td>X</td>
<td>Y</td>
</tr>
</table>
<p id="textout">#textout : </p>
You can do column.html(); to get the cell content
You could always try with break.
Link: MDN
Try to use break:
$('td:first-child').each(function() {
for (var i = 0; i <= 5; i++) {
var col = $('.tabell tr').find('td:nth-child(' + i + ').check').length;
if (col == 5) {
$(".bingocl").fadeIn(2000);
var column = $('.tabell tr').find('td:nth-child(' + i + ')');
column.addClass("bingo", 2000);
var text = column.text().toUpperCase();
$("#textout").append(text + "!!");
break;
}
}
});

jQuery TableSorter Plugin error : cannot read property '1' of undefined

I am trying to use the jquery table sorter plugin but I am getting error when I try to sort the table.
This is the error message:
cannot read property '1' of undefined
This is my html code:
<table id='tweetResult' class="tablesorter" style="width:500px;">
<thead>
<th>Photo</th>
<th>Name</>
<th>Status</th>
<th>Place Name</th>
<th>Coordinate</th>
<th>Created At</th>
</thead>
<tbody>
</tbody>
</table>
The tbody content is in js format:
$(document).ready(function(){
$("#tweetResult").tablesorter();
});
(function(){
var location = new Array();
var query = '%23CM0655';
var url = "search.php";
$.post(url, {query:query}, function(tweets){
console.log(tweets);
$("#tweetResult tbody").html("");
var geoEnabled = false;
var placeName = "";
var countryName = "";
for(var i=0; i<tweets.statuses.length; i++){
var row = $("<tr></tr>");
var img = $("<td><img src='" + tweets.statuses[i].user.profile_image_url + "' class='tweetpic'/></td>");
row.append(img);
// row.append($("<td></td>").html(tweets.statuses[i].user.screen_name));
row.append($("<td></td>").html(tweets.statuses[i].user.screen_name));
row.append($("<td></td>").html(tweets.statuses[i].text + "<br/>"));
geoEnabled = tweets.statuses[i].user.geo_enabled;
if(geoEnabled){
placeName = tweets.statuses[i].place.name;
countryName = tweets.statuses[i].place.country;
if(placeName != null){
row.append($("<td></td>").html(placeName + "," + countryName + "<br/>"));
}
row.append($("<td></td>").html("Location: " + tweets.statuses[i].place.bounding_box.coordinates[0][0][0] + ", " +
tweets.statuses[i].place.bounding_box.coordinates[0][0][1] + "<br/>"));
row.append($("<td></td>").html(tweets.statuses[i].created_at));
}
$("#tweetResult tbody").append(row)
}
});
setTimeout(arguments.callee, 60000);
})();
This is the console.log(tweets) output:
Object
search_metadata
:
Object
statuses
:
Array[10]
__proto__
:
Object
Can someone tell me how to fix this error. Thanks in advance.
i solved it by adding a timeout function
setTimeout(function(){
$('table').tablesorter();
}, 10000);

How to optimize jquery script (table creation N rows X 56 cols)

Hi I have a jquery scripts that takes table template and adds N rows (N=[1...100]) as clones of first TR. then each cell in each row is populated with some data (not all cells are always filled), each cell has " on clik " event attached, and on cell hover row, cell, coll is highlighted.
The problem i am facing is the optimization of generation (time) and usability (the mouse movemnts aren't smooth)
the code:
HTML template table:
<table id='schedulerview' class='myGrid'>
<colgroup id='col_0'></colgroup>
<colgroup id='col_1'></colgroup>
<colgroup id='col_2'></colgroup>
<colgroup id='col_3'></colgroup>
....
<colgroup id='col_55'></colgroup>
<thead>
<tr>
<th>0</th>
<th>1</th>
<th>2</th>
<th>3</th>
....
<th>51</th>
</tr>
</thead>
<tbody>
<tr id='template' style='display:none'>
<td id='0' HID='W0_Y_I' class='scheddata'>Week 1</td>
.....
<td id='51' HID='W55_Y_I' class='scheddata'>Week 52</td>
</tr>
</tbody>
</table>
CSS :
.litrow { background-color: #eee; }
.litcell { background-color: yellow; }
file codebehind.js
$(document).ready(function () {
//turn on row, cell, column highlight on hover
$("table#schedulerview tbody").on('mouseenter', 'tr', function () {
$(this).addClass('litrow');
});
$("table#schedulerview tbody").on('mouseleave', 'tr', function () {
$(this).removeClass('litrow');
});
$("table#schedulerview tbody").on('mouseenter', 'td', function () {
$(this).addClass('litcell');
$("colgroup").eq($(this).index()).addClass("litrow");
});
$("table#schedulerview tbody").on('mouseleave', 'td', function () {
$(this).removeClass('litcell');
$("colgroup").eq($(this).index()).removeClass("litrow");
});
//function for getting data and create schedule table from template table
getSchedule();
});
getschedule function:
function getSchedule() {
var data = "{userid:'" + userid + "',year:" + year + "}";
$.ajax({
type: "POST",
url: "/Scheduler.aspx/getSchedule",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (ret) {
var areas = JSON.parse(ret.d.Areas);
var schedule = JSON.parse(ret.d.Schedule);
//remove all rows from table that are not template
$('table#schedulerview tr.eventSchedule').remove();
//create row for each element from DB - prepare matrix elementsXWeeks
var $tr = $('#template');
$.each(areas, function (i, x) {
var $clone = $tr.clone();
$clone.css('display', 'block');
$clone.attr('id', 'new_row_' + i);
$clone.addClass('eventSchedule');
$clone.children('td:first').text(x.AreaName);
//for each cell in new row
$clone.children('td.scheddata').each(function () {
var $this = $(this);
var HID = $this.attr("HID").replace('_Y_', '_' + year + '_').replace('_I', '_' + x.IDObszaru);
$this.attr("HID", HID);
});
$tr.before($clone);
});
//fill in the matrix with scheduled data
$.each(schedule, function (i, x) {
$td = $("table#schedulerview td[HID='" + x.HID + "']");
$td.addClass(x.Status);
$td.attr("WeekNum", x.WeekNum);
$td.attr("PlanID", x.Id);
$td.parent().addClass('plannedrow');
});
},
error: function (ret) {
alert(ret.responseText);
}
});
}
The getSchedule() function lasts few seconds, is it possible to optimize it so it would be faster?
CHANGES:
I've tried different approach for row creation:
for (i = 0; i < areas.length; i++) {
$lasttr = $("table#schedulerview tbody").append("<tr id='new_row_" + i + "' class='eventSchedule' ></tr>");
$lasttr = $("table#schedulerview tbody tr#new_row_" + i);
for (j = 0; j < 56; j++) {
var sclass = "";
if (j == 0)
$lasttr.append("<td>" + areas[i].AreaName + "</td>");
if (j == 1)
$lasttr.append("<td>" + areas[i].AreaSubName + "</td>");
if (j == 2)
$lasttr.append("<td>" + areas[i].AreaParentName + "</td>");
if (j > 2) {
sclass = "'scheddata'";
k = j - 2;
$lasttr.append("<td class=" + sclass + " HID='W" + k + "_" + year + "_" + areas[i].AreaID + "'></td>");
}
}
}
but it's not fast enough- and the problem with hovering remains. (also when using css :hover pseudoclass.
Can you do something like this?
$(function () {
for (i = 0; i < 56; i++)
$("thead tr").append("<th>" + (i+1) +"</th>");
for (i = 0; i < 20; i++){
$("tbody").append("<tr />");
for (j = 0; j < 56; j++)
$("tbody tr:last-child").append("<td>" + ((i+1) + ": " + (j+1)) +"</td>");
}
});
table tr:hover td {background: #99f;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
<thead><tr></tr></thead>
<tbody></tbody>
</table>

creating a html table in javascript

I want to create HTML table in java script. Inside a for loop I want to create a dynamic table which can be extended. This is how I am it using now:
function(json)
{
var content= $('#name1').html('').append('<td> Name: ' + json.name + '<td>');
var content= $('#address1').html('').append('<td> address: ' + json.address + '<td>');
var content= $('#age1').html('').append('<td> age: ' + json.age + '<td>');
var content= $('#status1').html('').append('<td> status: ' + json.status + '<td>');
}
HTML file is
<table>
<tr id="name1"></tr>
<tr id="address1"></tr>
<tr id="age1"></tr>
<tr id="status1"></tr>
</table>
now it is just with hardcore values but I want it auto generated and insert more rows if neccessary...
remove id from tr. Because if you need multiple row then id will be duplicated which is not valid.
<table id="mytable">
</table>
function(json)
{
for(i=0;i<json.length;i++){
var newRow= $("<tr></tr>");
newRow.append('<td> Name: ' + json[i].name + '<td>');
newRow.append('<td> address: ' + json[i].address + '<td>');
newRow.append('<td> age: ' + json[i].age + '<td>');
newRow.append('<td> status: ' + json[i].status + '<td>');
$("#mytable").append(newRow);
}
}
i think this will help you
function(json)
{
for(i=0;i<jsn.length;i++){
$('#YOUR_TABLE_ID').append("<tr><td>"+ json.name+"</td></tr>")
}
}
<table id="mytable">
<tr id="name1"><td></td></tr>
</table>
if (results != null && results.length > 0) {
// Build our table header
var content = "";
for(i=0;i<data.length;i++)
{
content += '<tr>';
content += '<td></td>'
}
content += '</tr>';
}
$("#mytable tbody").append(content);
}
You can Use Append Method to create Rows in a table like
for(i=0;i<data.length;i++)
{
$("YOUR_TABLE_ID").append("<tr><td>"+data[i]['name']+"</td><td>"+data[i]['address']+"</td><td>"+data[i]['age']+"</td><td>"+data[i]['status']+"</td></tr>");
}
I'm not clear with your requirement but i can provide you some basic code hope that helps you.
var jsonList = [{name:'Jhon',address:'Jhon Address goes here',age:'27',status:'Single'},
{name:'Smith',address:'Smith Address goes here' ,age:'32', status:'Single' }];
function createTable(){
var table = '<table>';
for(var ind=0;ind< jsonList.length;ind++)
table += fetchRowInformation(jsonList[ind]);
console.log(table+'</table>');
}
function fetchRowInformation(json){
return '<tr><td> Name: ' + json.name + '<td>'+'<td> address: ' + json.address + '<td>'+ '<td> age: ' + json.age + '<td>'+'<td> status: ' + json.status + '<td></tr>';
}
JS Fiddle Demo
function tableCreate(rows, columns) {
var body = document.body
tbl = document.createElement('table');
tbl.style.width = '20%';
tbl.style.border = '1px solid black';
for (var i = 0; i < rows; i++) {
var tr = tbl.insertRow();
for (var j = 0; j < columns; j++) {
var td = tr.insertCell();
td.appendChild(document.createTextNode('Cell'));
td.style.border = '1px solid black';
}
}
tbl.style.marginTop = '10px'
tbl.style.borderCollapse = 'collapse'
td.style.padding = '2px'
body.appendChild(tbl);
}
tableCreate(15, 10);

Categories