Javascript Parsing Table Content to Json - javascript

I have table structure like this:
<figure class="table">
<table>
<tbody>
<tr>
<td>[11]</td>
<td>[12]</td>
<td>[13]</td>
</tr>
</tbody>
</table>
</figure>
and I need to parse the table content [11], [12], [13] to json below:
{
“block_id”: 11
},
{
“block_id”: 12
},
{
“block_id”: 13
}
Is there a way using javascript to parse the table contents to json?
Please help.. Thank you

Solution: Just assign an ID to the table body and pass that element to the function!
Table:
<table>
<tbody id="table_body">
<tr>
<td>[11]</td>
<td>[12]</td>
<td>[13]</td>
</tr>
<tr>
<td>[14]</td>
<td>[15]</td>
<td>[16]</td>
</tr>
</tbody>
</table>
JS:
function tableToJson(table) {
var tableObject = [];
for(i = 0 ; i < table.length ; i ++)
{
var row = [];
for(j = 0 ; j < table[i].children.length; j++)
{
row.push(table[i].children[j].innerHTML);
}
tableObject.push(row);
}
return tableObject;
}
console.log(
JSON.stringify(
tableToJson(document.getElementById("table_body").children)
)
);
Hope this helps! :)

you can add jQuery, than assign id to and itrate the values using foreach loop.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<table>
<tbody>
<tr id="myTr">
</tr>
</tbody>
<script>
$(function(){
var myArr = [{"block_id": 11},{"block_id": 12},{"block_id": 13}];
$('#myTr').html('');
$.each( obj, function( key, value ) {
$('#myTr').append('<td>'+value.block_id+'</td>');
});
});
</script>

Related

I'd like to create a JSON object out of an HTML table. I'd like the end product to be used to tally input from multiple users

Active learner here, trying to figure out how to create a JSON object out of HTML table. I only want the value of one specific TD and want to give each value an incrementing number as a key. I'd like an output like below. My table has a TD for the city names, but it does not have one with a incrementing numerical value so I'd need to add that another way.
{
"mycities" : [
{
"Seattle" : "1",
"Chicago" : "2",
"New York" : "3"
"Pitt" : "4",
"LA" : "5",
"Fresno" : "6"
},
]
}
Here is what my table looks like:
<table>
<thead>
<tr>
<th>city name</th>
<th>other city info</th>
</tr>
</thead>
<tbody>
<tr>
<td>Seattle</td>
<td>Lots of rain</td>
</tr>
etc,etc,etc
</tbody>
</table>
I've tried using a replacer function but haven't got it figured out after much googling. Any help is appreciated!
$(document).ready(function(){
$("body").on("click",".submitButtonPri",function(){
count= 1;
function replacer(key, value) {
if (typeof value === 'string') {
return count;
}
return value;
}
var myRows = [];
var $headers = $(".rightDash > table thead th");
var $rows = $(".rightDash > table tbody tr").each(function(index) {
$cells = $(this).find("td.titlePri");
myRows[index] = {};
$cells.each(function(cellIndex) {
myRows[index][$($cells[cellIndex]).text()] = $(this).text();
});
count++;
});
var myObj = {};
myObj.myrows = myRows;
console.log(JSON.stringify(myObj,replacer));
});
});
Use reduce to iterate over the trs in the body, using the text content of the first td in the tr as the city name. The third argument to the function provided to reduce represents the iteration index:
const cityData = [...document.querySelectorAll('tbody > tr')]
.reduce((a, tr, i) => {
a[tr.children[0].textContent] = i + 1;
return a;
}, {});
console.log(
{ mycities: [
cityData
]}
);
<table>
<thead>
<tr>
<th>city name</th>
<th>other city info</th>
</tr>
</thead>
<tbody>
<tr>
<td>Seattle</td>
<td>Lots of rain</td>
</tr>
<tr>
<td>Chicago</td>
<td>Lots of rain</td>
</tr>
<tr>
<td>New York</td>
<td>Lots of rain</td>
</tr>
</tbody>
</table>
You can start with this simple script:
$('td').each(function(index, obj) {console.log(index, $(this).html())});
It returns all what you need and you just need assemble JSON by any way

generating table with text box

I've a bit of experience coding in php but am fairly new to js. What I'm trying to do in js is create a simple order form, each line is to have a text box indicating the quantity to be ordered, product name and product price, with the latter to be populated from product array prod. My fairly rudimentary first attempt appears below, which needless to say doesn't work.
<body onload="populate()">
<table id="demo">
<thead>
<tr>
<th>Quantity</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
function populate(){
var prod; //array of objects with name and price attributes
var table = document.getElementById("theTable");
for (var i=0; i<prod.length; i++)
{
var newTr = table.insertRow(-1);
var numOrdered=document.createElement('input');
numOrdered.type='text';
numOrdered.id= "product "+i; //assigning id of "product i" to each product i
newTr.insertCell(0).appendChild(num);
newTr.insertCell(-1).appendChild(document.createTextNode(prod["name"]));
newTr.insertCell(-1).appendChild(document.createTextNode(prod["price"]));
}
}
</script>
</body>
Any and all help appreciated.
have a look at the snippet at the bottom.
what's changed is:
in this line you targeted the wrong id, should have been 'demo'
var table = document.getElementById("theTable");
you also needed to reference the correct value in your array inside the loop:
document.createTextNode(prod["name"]);
to:
document.createTextNode(prod[i]["name"]);
and lastly this line:
newTr.insertCell(0).appendChild(num);
to:
newTr.insertCell(0).appendChild(numOrdered);
hope this helps.
function populate() {
var prod = [{
name: 'box',
price: 20
}, {
name: 'plane',
price: 40
}]; //array of objects with name and price attributes
var table = document.getElementById("theTable");
for (var i = 0; i < prod.length; i++) {
var newTr = table.insertRow(-1);
var numOrdered = document.createElement('input');
numOrdered.type = 'text';
numOrdered.id = "product " + i; //assigning id of "product i" to each product i
newTr.insertCell(0).appendChild(numOrdered);
newTr.insertCell(-1).appendChild(document.createTextNode(prod[i]["name"]));
newTr.insertCell(-1).appendChild(document.createTextNode(prod[i]["price"]));
}
}
populate();
<table id="theTable">
<thead>
<tr>
<th>Quantity</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
Try This code:
I am using jQuery, to create, append and iterating the array(each Loop).It is a better and effective way. Please use jQuery for DOM manipulation.
HTML:
<table id="demo">
<thead>
<tr>
<th>Quantity</th>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
CSS:
table,td{display:block}
th{width:100px}
td{margin:10px}
JS:
var prod=[{product:'samsung',price:100},{product:'apple',price:200},{product:'micromax',price:300}];
(function($){
$.each(prod,function(index,value){
$('#demo th:eq(0)').append("<td><input type='text'></td>");
$('#demo th:eq(1)').append("<td>"+value.product.toUpperCase()+"</td>");
$('#demo th:eq(2)').append("<td>"+value.price+"</td>")
});
})(jQuery);
Here is the JSFiddle Link:
https://jsfiddle.net/Dee0565/8vww1pwf/

Find table data store in within an array of arrays

I need to get data from a table and store it in an array. Each row of the table should be a new array within an array. Basically the html looks like this:
<table id="contactlisttable">
<tr>
<th>Name</th>
<th>Title</th>
<th>Phone</th>
</tr>
<tr>
<td class="contactlist contactlistlastfirst">Joey</td>
<td class="contactlist contactlisttitle">webdesigner</td>
<td class="contactlist contactlistphone">5555555</td>
</tr>
<tr>
<td class="contactlist contactlistlastfirst">Anthony</td>
<td class="contactlist contactlisttitle">webdesigner</td>
<td class="contactlist contactlistphone">5555555</td>
</tr>
</table>
ect...
Here is my code
jQuery(document).ready(function(){
$(function(){
var $table = $("#contactlisttable"),
$headerCells = $table.find("tr th"),
$myrows = $table.find("tr"); // Changed this to loop through rows
var headers = [],
rows = [];
$headerCells.each(function() {
headers[headers.length] = $(this).text();
});
$myrows.each(function() {
$mycells = $myrows.find( "td.contactlist" ); // loop through cells of each row
cells = []
$mycells.each(function() {
cells.push($(this).text());
});
if ( cells.length > 0 ) {
rows.push(cells);
}
});
console.log(headers);
console.log(rows);
});
});
my current code out puts
[["Waddell, Joey", "webdesigner", "", 15 more...], ["Waddell, Joey", "webdesigner", "", 15 more...],
the desired output would be:
["Name","Title","Phone"]
[["Joey","webdesigner","555555"]
["Anthony","webdesigner","555555"]]
I think this can be simpler:
Live Demo
JS
$(function(){
var results = [];
var row = -1;
$('#contactlisttable').find('th, td').each(function(i, val){
if(i % 3 === 0){ //New Row?
results.push([]);
row++;//Increment the row counter
}
results[row].push(this.textContent || this.innerText); //Add the values (textContent is standard while innerText is not)
});
console.log(results);
});
EDIT
Here's an even better solution (IE9+ compatible). It accounts for variable row lengths unlike my previous solution.
Live Demo
JS
//IE9+ compatable solution
$(function(){
var results = [], row;
$('#contactlisttable').find('th, td').each(function(){
if(!this.previousElementSibling){ //New Row?
row = [];
results.push(row);
}
row.push(this.textContent || this.innerText); //Add the values (textContent is standard while innerText is not)
});
console.log(results);
});

how to convert/transform an HTML table tbody (with rowspans) TO json?

I have an HTML table with combined row td's, or how to say, I don't know how to express myself (I am not so good at English), so I show it! This is my table:
<table border="1">
<thead>
<tr>
<th>line</th>
<th>value1</th>
<th>value2</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="2">1</td>
<td>1.1</td>
<td>1.2</td>
</tr>
<tr>
<td>1.3</td>
<td>1.4</td>
</tr>
<tr>
<td rowspan="2">2</td>
<td>2.1</td>
<td>2.2</td>
</tr>
<tr>
<td>2.3</td>
<td>2.4</td>
</tr>
</tbody>
</table>
(you can check it here)
I want to convert this table to a JSON variable by jquery or javascript.
How should it look like, and how should I do it? Thank you, if you can help me!
if you want to convert only text use this one :
var array = [];
$('table').find('thead tr').each(function(){
$(this).children('th').each(function(){
array.push($(this).text());
})
}).end().find('tbody tr').each(function(){
$(this).children('td').each(function(){
array.push($(this).text());
})
})
var json = JSON.stringify(array);
To make a somehow representation of your table made no problem to me, but the problem is how to parse it back to HTML! Here a JSON with the first 6 tags:
{"table":{"border":1,"thead":{"th":{"textContent":"line","tr":"textContent":"value1",...}}}}}...
OR for better understanding:
{"tag":"table","border":1,"child":{"tag":"thead","child":{"tag":"th","textContent":"line",
"child":{"tag":"tr","textContent":"value1","child":...}}}}...
Closing tags are included.
For further explanations I need to know whether your table is a string or part of the DOM.
I belive this is what you want:
var jsonTable = {};
// add a new array property named: "columns"
$('table').find('thead tr').each(function() {
jsonTable.columns = $(this).find('th').text();
};
// now add a new array property which contains your rows: "rows"
$('table').find('tbody tr').each(function() {
var row = {};
// add data by colum names derived from "tbody"
for(var i = 0; i < jsonTable.columnsl.length; i++) {
row[ col ] = $(this).find('td').eq( i ).text();
}
// push it all to the results..
jsonTable.rows.push( row );
};
alert(JSON.stringify(jsonTable));
I think there should be some corrections, but this is it I think.

create json object from html table using selected colums using jquery

i was wondering how to parse html table to get json object that i can send via $.post with jquery.
i have a table
<table id="Report">
<thead>
<tr>
<th>Kod</th>
<th>Nazwa</th>
<th>Ilość</th>
<th>Netto / 1szt.</th>
<th>Suma brutto</th>
</tr>
</thead>
<tbody>
<tr>
<td>00171 </td>
<td>SŁUP 50/1800 POŚREDNI(P) </td>
<td>5</td><td>97.00 PLN </td>
<td>394.31 PLN </td>
</tr>
<tr>
<td>00172</td>
<td>SŁUP 50/1800 NAROŻNY(P)</td>
<td>1</td><td>97.00 PLN</td>
<td>78.86 PLN</td>
</tr>
<tr>
<td>00173 </td>
<td>SŁUP 50/1800 KOŃCOWY(P) </td>
<td>1</td><td>97.00 PLN </td>
<td>78.86 PLN</td>
</tr>
</tbody>
<tfoot style="font-weight: bold;">
<tr>
<th colspan="3" style="text-align: right;">Razem netto: 1955.85 PLN</th>
<th colspan="2" style="text-align: right;">Razem brutto: 2405.69 PLN</th>
</tr>
</tfoot>
</table>
and what i need is json object in this format (first <td> and third <td>):
[{"00171":5},
{"00172":1},
{"00173":1}
]
and that i can send it via
$.post(
"print.php",
{json: myjsonvar},
"json"
);
any idea how to do that?
thanks
var json = [];
$('#Report').find('tbody tr').each(function(){
var obj = {},
$td = $(this).find('td'),
key = $td.eq(0).text(),
val = parseInt( $td.eq(2).text(), 10 );
obj[key] = val;
json.push(obj);
});
How about:
var myjsonvar=[];
$('#Report tbody tr').each(function(){
var data={};
var tr=$(this);
data[tr.find('td:first-child').text()]=tr.find('td:nth-child(3)').text();
myjsonvar.push(data);
});
var sendData = [];
$('#Report tbody tr').each(function(i, el){
var key = $.trim($(this).find('td:eq(0)').text()),
val = $.trim($(this).find('td:eq(2)').text()),
obj = {};
obj[key] = val;
sendData.push(obj);
});
See demo
Why json, if you are in js already? Just create a simple object:
var data = {};
$("#Report tbody tr").each(function() {
data[$(this).children("td:eq(0)").text()] = $(this).children("td:eq(2)").text();
});
$.post("print.php", data);
Setting type to json in $.post defines the server response to be json, not the send data!
http://jsfiddle.net/zyCPN/
var objArray=[];
$('table#Report tbody tr').each(function(i){
var row=$(this);
obj={};
obj[$('td', row).eq(0).text()]=$('td', row).eq(2).text();
objArray.push(obj);
});

Categories