Convert a HTML Table to JSON

Converting Html Table to JSON

something like that would work (not really nice, but)

Explanation :

You can use ignoreColumns to avoid taking columns 3 and 4.

You can use headings to change the "headers" (keys in the json file). But this will take also the first line (the one with the TH).

So we have to remove that first line after building the json array.

$('#convert-table').click( function() {
var $table = $('#example-table');

var table = $table.tableToJSON(
{
ignoreColumns:[3, 4],
headings: ['FirstName', 'LastName', 'Score']
});
var newTable = $.map(table, function(e){
return (e.FirstName == "Person Name") ? null : e;
});
console.log(newTable);
alert(JSON.stringify(newTable));
});

see jsfiddle

EDIT

If the number of columns with Person Name is dynamic, you could do something like that (assuming you never want the two last rows)

function convertToTable(el, numberOfColumns, columnNames) {
var columnsToIgnore = [numberOfColumns-2, numberOfColumns-1];
var table = el.tableToJSON(
{
ignoreColumns:columnsToIgnore,
headings: columnNames
});
var result = $.map(table, function(e){
return (e['Person Name0'] == "Person Name") ? null : e;
});
alert(JSON.stringify(result));
}

$('#convert-table').click( function() {
var $table = $('#example-table');
var columns = $table.find('th');
var numberOfColumns = columns.length;
var columnNames = columns.map(function(index) {
var text = $(this).text();
return text == 'Person Name' ? text + index : text;
}).get();

convertToTable($table, numberOfColumns, columnNames);
});

see JsFiddle

convert a html table with select to Json

One way is use the index in the extractor. When index is one return the value of the select, otherwise return the cell text

$('#run').click(function() {
var table = $('#students').tableToJSON({
extractor: function($index, $cell) {
if ($index == 1) {
return $cell.find('select').val()
}
return $cell.text()
}
});
console.log(JSON.stringify(table));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/table-to-json@1.0.0/lib/jquery.tabletojson.min.js" integrity="sha256-H8xrCe0tZFi/C2CgxkmiGksqVaxhW0PFcUKZJZo1yNU=" crossorigin="anonymous"></script>
<table id="students" border="1">
<thead>
<tr>
<th>Name</th>
<th> Animal </th>
<th>Age</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<tr>
<td>Oscar</td>
<td>
<select name="pets" id="pet-select">

<option value="dog">Dog</option>
<option value="cat" selected>Cat</option>
<option value="hamster">Hamster</option>
</select>
</td>
<td>23</td>
<td>16.5</td>
</tr>
<tr>
<td>Antonio</td>
<td>
<select name="pets" id="pet-select">

<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="hamster" selected>Hamster</option>

</select>
</td>
<td>32</td>
<td>14</td>
</tr>
<tr>
<td>Jessica</td>
<td>
<select name="pets" id="pet-select">

<option value="dog" selected>Dog</option>
<option value="cat">Cat</option>
<option value="hamster">Hamster</option>

</select>
</td>
<td>21</td>
<td>19</td>
</tr>
</tbody>
</table>
<br>
<button id="run">Convert!</button>

create a json array from html table

Here's my implementation:

var tableToObj = function( table ) {
var trs = table.rows,
trl = trs.length,
i = 0,
j = 0,
keys = [],
obj, ret = [];

for (; i < trl; i++) {
if (i == 0) {
for (; j < trs[i].children.length; j++) {
keys.push(trs[i].children[j].innerHTML);
}
} else {
obj = {};
for (j = 0; j < trs[i].children.length; j++) {
obj[keys[j]] = trs[i].children[j].innerHTML;
}
ret.push(obj);
}
}

return ret;
};

Which you would invoke like:

var obj = tableToObj( document.getElementsByTagName('table')[0] ); // or
var obj = tableToObj( document.getElementById('myTable') );

See working example →

How to convert the following table to JSON with javascript?

Update: There's a slightly improved fork of the solution (below) on jsFiddle.

You just need to walk the DOM of your table reading it out... this is not even close to optimized but will give you the result you want. (jsFiddle)

// Loop through grabbing everything
var myRows = [];
var $headers = $("th");
var $rows = $("tbody tr").each(function(index) {
$cells = $(this).find("td");
myRows[index] = {};
$cells.each(function(cellIndex) {
myRows[index][$($headers[cellIndex]).html()] = $(this).html();
});
});

// Let's put this in the object like you want and convert to JSON (Note: jQuery will also do this for you on the Ajax request)
var myObj = {};
myObj.myrows = myRows;
alert(JSON.stringify(myObj));​

And the output...

{"myrows":[{"Column 1":"A1","Column 2":"A2","Column 3":"A3"},{"Column 1":"B1","Column 2":"B2","Column 3":"B3"},{"Column 1":"C1","Column 2":"C2","Column 3":"C3"}]}

Convert table HTML to JSON

Assuming all you need is to get the first/second cells of each row as key/value pairs, you can use .reduce() to iterate of the rows and just grab the text content of .cells[0] and .cells[1] to use as each key/value pair:

var t = document.querySelector("table");
var j = [].reduce.call(t.rows, function(res, row) { res[row.cells[0].textContent.slice(0,-1)] = row.cells[1].textContent; return res}, {});
document.querySelector("pre").textContent = JSON.stringify(j, null, 2);
<table>    <tr>        <th>Name:</th>        <td>Carlos</td>    </tr>            <tr>        <th>Age:</th>        <td>22</td>    </tr></table><pre></pre>

How to convert value from HTML table to JSON array in javascript

This will do the job:

const res=[...document.querySelectorAll("#stockinboundedittable tr")].slice(1).map(tr=>
[...tr.querySelectorAll("input")].slice(0).map(inp=>[inp.id.replace(/.*inboundedit/,"").replace(/\d+$/,""),inp.value]))
.reduce((a,c)=>{
a[c[0][1]]=
Object.fromEntries(c.slice(1));
return a},{});

console.log(res[2]);
<table style="width:100%;   border-collapse: collapse;  text-align: center;" id="stockinboundedittable">

<tr>
<th style="display:none;">subcategory</th>
<th>Sl.No</th>
<!--<th>I.U.Code</th>-->
<th>Item Name</th>
<th> old stock</th>
<th> new stock</th>
<th> Total Stock</th>
<th> qrt</th>
<th>Edit</th>
</tr>

<tr>
<td style="display:none;">tmcsubctgy_2</td>
<td>
<input style=" width: 100%;" id="slno1editinbound1" value="1" readonly="">
</td>
<td>
<input style=" width: 100%;" id="stockinboundedititemname1" value="Fresh Goat Meat - Curry Cut" readonly="">
</td>
<td>
<input style=" width: 100%;" id="stockinboundeditoldstock1" value="20" readonly="">
</td>
<td>
<input style=" width: 100%;" id="stockinboundeditnewstock1" value="10" readonly="">
</td>
<td>
<input style=" width: 100%;" id="stockinboundedittotalstock1" value="30" readonly="">
</td>
<td>
<input style=" width: 100%;" id="inboundeditqty1">
</td>
<td>
<button style="background: #fdd110; width: 100%;" id="stockinboundeditditbut1">EDIT</button>
</td>
</tr>
<tr>
<td style="display:none;">tmcsubctgy_5</td>
<td>
<input style=" width: 100%;" id="slno1editinbound2" value="2" readonly="">
</td>
<td>
<input style=" width: 100%;" id="stockinboundedititemname2" value="Everest - Kasur Methi" readonly="">
</td>
<td>
<input style=" width: 100%;" id="stockinboundeditoldstock2" value="0" readonly="">
</td>
<td>
<input style=" width: 100%;" id="stockinboundeditnewstock2" value="10" readonly="">
</td>
<td>
<input style=" width: 100%;" id="stockinboundedittotalstock2" value="10" readonly="">
</td>
<td>
<input style=" width: 100%;" id="inboundeditqty2">
</td>
<td>
<button style="background: #fdd110; width: 100%;" id="stockinboundeditditbut2">EDIT</button>
</td>
</tr>
<tr>
<td style="display:none;">tmcsubctgy_13</td>
<td>
<input style=" width: 100%;" id="slno1editinbound3" value="3" readonly="">
</td>
<td>
<input style=" width: 100%;" id="stockinboundedititemname3" value="Fresh Coconut Milk 150 ml" readonly="">
</td>
<td>
<input style=" width: 100%;" id="stockinboundeditoldstock3" value="10" readonly="">
</td>
<td>
<input style=" width: 100%;" id="stockinboundeditnewstock3" value="10" readonly="">
</td>
<td>
<input style=" width: 100%;" id="stockinboundedittotalstock3" value="20" readonly="">
</td>
<td>
<input style=" width: 100%;" id="inboundeditqty3">
</td>
<td>
<button style="background: #fdd110; width: 100%;" id="stockinboundeditditbut3">EDIT</button>
</td>
</tr>
<tr>
<td style="display:none;">tmcsubctgy_5</td>
<td>
<input style=" width: 100%;" id="slno1editinbound4" value="4" readonly="">
</td>
<td>
<input style=" width: 100%;" id="stockinboundedititemname4" value="Sakthi - Chicken Masala" readonly="">
</td>
<td>
<input style=" width: 100%;" id="stockinboundeditoldstock4" value="20" readonly="">
</td>
<td>
<input style=" width: 100%;" id="stockinboundeditnewstock4" value="10" readonly="">
</td>
<td>
<input style=" width: 100%;" id="stockinboundedittotalstock4" value="30" readonly="">
</td>
<td>
<input style=" width: 100%;" id="inboundeditqty4">
</td>
<td>
<button style="background: #fdd110; width: 100%;" id="stockinboundeditditbut4">EDIT</button>
</td>
</tr>
<tr>
<td style="display:none;">tmcsubctgy_2</td>
<td>
<input style=" width: 100%;" id="slno1editinbound5" value="5" readonly="">
</td>
<td>
<input style=" width: 100%;" id="stockinboundedititemname5" value="Goat Bones - Regular Soup Pack" readonly="">
</td>
<td>
<input style=" width: 100%;" id="stockinboundeditoldstock5" value="0" readonly="">
</td>
<td>
<input style=" width: 100%;" id="stockinboundeditnewstock5" value="10" readonly="">
</td>
<td>
<input style=" width: 100%;" id="stockinboundedittotalstock5" value="10" readonly="">
</td>
<td>
<input style=" width: 100%;" id="inboundeditqty5">
</td>
<td>
<button style="background: #fdd110; width: 100%;" id="stockinboundeditditbut5">EDIT</button>
</td>
</tr>
</table>
</table>

Convert HTML table with a header to Json - Python

This code does exactly what you want

from bs4 import BeautifulSoup
import json

xml_data = """
[[your xml data]]"""

if __name__ == '__main__':
model = BeautifulSoup(xml_data, features='lxml')
fields = []
table_data = []
for tr in model.table.find_all('tr', recursive=False):
for th in tr.find_all('th', recursive=False):
fields.append(th.text)
for tr in model.table.find_all('tr', recursive=False):
datum = {}
for i, td in enumerate(tr.find_all('td', recursive=False)):
datum[fields[i]] = td.text
if datum:
table_data.append(datum)

print(json.dumps(table_data, indent=4))

Convert HTML Table to JSON (Python)

I tried to make this solution as generic as possible while also fulfilling the specific case presented. This will only work for the second case, as without th elements or specific classes only on header elements, it cannot be determined whether the headers are vertical or horizontal programmatically.

from bs4 import BeautifulSoup
from pathlib import Path
import itertools

html_data = Path("table.html").read_text()
table_data = [[td.text.strip() for td in tr("td") if td.text.strip()]
for tr in BeautifulSoup(html_data, features="lxml")("tr")]

out = [{t: rest if len(rest) > 1 else rest[0]} for k, g in
itertools.groupby(table_data, key=bool) if k for t, *rest in zip(*g)]
print(out)

output:

[{'Pickup Location': 'Some Address'}, {'Description': 'Rubics cube'}, {'PLTS': ['1', '2']}, {'total weight': ['20', '60']}, {'L': ['40', '40']}, {'W': ['40', '40']}, {'H': ['40', '40']}]

table.html

<table>
<tbody>
<tr style="height:15.0pt">
<td colspan="2"
style="width:130.9pt; border-top:solid windowtext 1.0pt; border-left:none; border-bottom:solid windowtext 1.0pt; border-right:solid black 1.0pt; padding:0in 5.4pt 0in 5.4pt; height:15.0pt"
width="175">
<p class="MsoNormal" style="text-align:center" align="center"><b><span
style="font-size:10.0pt; font-family:"Arial",sans-serif; color:black">Pickup Location</span></b>
</p>
</td>
<td colspan="3"
style="width:130.1pt; border-top:solid windowtext 1.0pt; border-left:none; border-bottom:solid windowtext 1.0pt; border-right:solid black 1.0pt; padding:0in 5.4pt 0in 5.4pt; height:15.0pt"
width="173">
<p class="MsoNormal" style="text-align:center" align="center"><b><span
style="font-size:10.0pt; font-family:"Arial",sans-serif; color:black">Description</span></b>
</p>
</td>
<td style="width:1.5pt; padding:0in 0in 0in 0in; height:15.0pt" width="2">
<p class="MsoNormal"></p>
</td>
<td style="width:.3pt; padding:0in 0in 0in 0in; height:15.0pt" width="0"></td>
</tr>
<tr style="height:13.15pt">
<td colspan="2" rowspan="2"
style="width:130.9pt; border-top:none; border-left:none; border-bottom:solid black 1.0pt; border-right:solid windowtext 1.0pt; padding:0in 5.4pt 0in 5.4pt; height:13.15pt"
width="175">
<p class="MsoNormal" style="text-align:center" align="center"><b><span
style="font-size:10.0pt; font-family:"Arial",sans-serif; color:black">Some Address</span></b>
</p>
</td>
<td colspan="3" rowspan="2"
style="width:130.1pt; border-top:none; border-left:none; border-bottom:solid black 1.0pt; border-right:solid black 1.0pt; padding:0in 5.4pt 0in 5.4pt; height:13.15pt"
width="173">
<p class="MsoNormal" style="text-align:center" align="center"><b><span
style="font-size:10.0pt; font-family:"Arial",sans-serif; color:black">Rubics cube</span></b>
</p>
</td>
<td style="width:1.5pt; padding:0in 0in 0in 0in; height:13.15pt" width="2">
<p class="MsoNormal"></p>
</td>
<td style="width:.3pt; padding:0in 0in 0in 0in; height:13.15pt" width="0"></td>
</tr>
<tr style="height:15.75pt">
</tr>
<tr style="height:.3in">
<td style="width:42.15pt; border-top:none; border-left:none; border-bottom:solid windowtext 1.0pt; border-right:solid windowtext 1.0pt; background:#D9E1F2; padding:0in 5.4pt 0in 5.4pt; height:.3in"
width="56" valign="bottom" nowrap="nowrap">
<p class="MsoNormal" style="text-align:center" align="center"><b><span
style="font-size:10.0pt; font-family:"Arial",sans-serif; color:black">PLTS</span></b><b><span
style="font-size:10.0pt; font-family:"Arial",sans-serif"></span></b></p>
</td>
<td style="width:88.75pt; border-top:none; border-left:none; border-bottom:solid windowtext 1.0pt; border-right:solid windowtext 1.0pt; background:#D9E1F2; padding:0in 5.4pt 0in 5.4pt; height:.3in"
width="118" valign="bottom" nowrap="nowrap">
<p class="MsoNormal" style="text-align:center" align="center"><b><span
style="font-size:10.0pt; font-family:"Arial",sans-serif; color:black">total weight</span></b><b><span
style="font-size:10.0pt; font-family:"Arial",sans-serif"></span></b></p>
</td>
<td style="width:20.15pt; border-top:none; border-left:none; border-bottom:solid windowtext 1.0pt; border-right:solid windowtext 1.0pt; background:#D9E1F2; padding:0in 5.4pt 0in 5.4pt; height:.3in"
width="27" valign="bottom" nowrap="nowrap">
<p class="MsoNormal" style="text-align:center" align="center"><b><span
style="font-size:10.0pt; font-family:"Arial",sans-serif; color:black">L</span></b><b><span
style="font-size:10.0pt; font-family:"Arial",sans-serif"></span></b></p>
</td>
<td style="width:20.15pt; border-top:none; border-left:none; border-bottom:solid windowtext 1.0pt; border-right:solid windowtext 1.0pt; background:#D9E1F2; padding:0in 5.4pt 0in 5.4pt; height:.3in"
width="27" valign="bottom" nowrap="nowrap">
<p class="MsoNormal" style="text-align:center" align="center"><b><span
style="font-size:10.0pt; font-family:"Arial",sans-serif; color:black">W</span></b><b><span
style="font-size:10.0pt; font-family:"Arial",sans-serif"></span></b></p>
</td>
<td style="width:17.0pt; border-top:none; border-left:none; border-bottom:solid windowtext 1.0pt; border-right:solid windowtext 1.0pt; background:#D9E1F2; padding:0in 5.4pt 0in 5.4pt; height:.3in"
width="23" valign="bottom" nowrap="nowrap">
<p class="MsoNormal" style="text-align:center" align="center"><b><span
style="font-size:10.0pt; font-family:"Arial",sans-serif; color:black">H</span></b><b><span
style="font-size:10.0pt; font-family:"Arial",sans-serif"></span></b></p>
</td>
</tr>
<tr style="height:13.9pt">
<td style="width:42.15pt; border-top:none; border-left:none; border-bottom:solid windowtext 1.0pt; border-right:solid windowtext 1.0pt; padding:0in 5.4pt 0in 5.4pt; height:13.9pt"
width="56" valign="bottom" nowrap="nowrap">
<p class="MsoNormal" style="text-align:center" align="center"><span
style="font-size:12.0pt; font-family:"Arial",sans-serif; color:black">1</span></p>
</td>
<td style="width:88.75pt; border-top:none; border-left:none; border-bottom:solid windowtext 1.0pt; border-right:solid windowtext 1.0pt; padding:0in 5.4pt 0in 5.4pt; height:13.9pt"
width="118" valign="bottom" nowrap="nowrap">
<p class="MsoNormal" style="text-align:center" align="center"><span
style="font-size:12.0pt; font-family:"Arial",sans-serif">20</span></p>
</td>
<td style="width:20.15pt; border-top:none; border-left:none; border-bottom:solid windowtext 1.0pt; border-right:solid windowtext 1.0pt; padding:0in 5.4pt 0in 5.4pt; height:13.9pt"
width="27" valign="bottom" nowrap="nowrap">
<p class="MsoNormal" style="text-align:center" align="center"><span
style="font-size:12.0pt; font-family:"Arial",sans-serif">40</span></p>
</td>
<td style="width:20.15pt; border-top:none; border-left:none; border-bottom:solid windowtext 1.0pt; border-right:solid windowtext 1.0pt; padding:0in 5.4pt 0in 5.4pt; height:13.9pt"
width="27" valign="bottom" nowrap="nowrap">
<p class="MsoNormal" style="text-align:center" align="center"><span
style="font-size:12.0pt; font-family:"Arial",sans-serif">40</span></p>
</td>
<td style="width:17.0pt; border-top:none; border-left:none; border-bottom:solid windowtext 1.0pt; border-right:solid windowtext 1.0pt; padding:0in 5.4pt 0in 5.4pt; height:13.9pt"
width="23" valign="bottom" nowrap="nowrap">
<p class="MsoNormal" style="text-align:center" align="center"><span
style="font-size:12.0pt; font-family:"Arial",sans-serif">40</span></p>
</td>
<td style="width:.3pt; padding:0in 0in 0in 0in; height:13.9pt" width="0"></td>
</tr>
<tr style="height:13.15pt">
<td style="width:42.15pt; border-top:none; border-left:none; border-bottom:solid windowtext 1.0pt; border-right:solid windowtext 1.0pt; padding:0in 5.4pt 0in 5.4pt; height:13.15pt"
width="56" valign="bottom" nowrap="nowrap">
<p class="MsoNormal" style="text-align:center" align="center"><span
style="font-size:12.0pt; font-family:"Arial",sans-serif; color:black">2</span></p>
</td>
<td style="width:88.75pt; border-top:none; border-left:none; border-bottom:solid windowtext 1.0pt; border-right:solid windowtext 1.0pt; padding:0in 5.4pt 0in 5.4pt; height:13.15pt"
width="118" valign="bottom" nowrap="nowrap">
<p class="MsoNormal" style="text-align:center" align="center"><span
style="font-size:12.0pt; font-family:"Arial",sans-serif">60</span></p>
</td>
<td style="width:20.15pt; border-top:none; border-left:none; border-bottom:solid windowtext 1.0pt; border-right:solid windowtext 1.0pt; padding:0in 5.4pt 0in 5.4pt; height:13.15pt"
width="27" valign="bottom" nowrap="nowrap">
<p class="MsoNormal" style="text-align:center" align="center"><span
style="font-size:12.0pt; font-family:"Arial",sans-serif">40</span></p>
</td>
<td style="width:20.15pt; border-top:none; border-left:none; border-bottom:solid windowtext 1.0pt; border-right:solid windowtext 1.0pt; padding:0in 5.4pt 0in 5.4pt; height:13.15pt"
width="27" valign="bottom" nowrap="nowrap">
<p class="MsoNormal" style="text-align:center" align="center"><span
style="font-size:12.0pt; font-family:"Arial",sans-serif">40</span></p>
</td>
<td style="width:17.0pt; border-top:none; border-left:none; border-bottom:solid windowtext 1.0pt; border-right:solid windowtext 1.0pt; padding:0in 5.4pt 0in 5.4pt; height:13.15pt"
width="23" valign="bottom" nowrap="nowrap">
<p class="MsoNormal" style="text-align:center" align="center"><span
style="font-size:12.0pt; font-family:"Arial",sans-serif">40</span></p>
</td>
</tr>
</tbody>
</table>

How to Convert HTML Table to JSON in PHP

I prefer to use XPath with DomDocument because of utility/ease of the syntax. By targeting the only the <tr> elements inside the <tbody> tag, you can access all required data.

With the exception of the href value, the final "all-letters" substring in each <td> class value represents your desired key for the associated value. For this I am using preg_match() to extract the final "word" in the class attribute.

When the $key is name, the href attribute value must be stored with the hardcode key: user_link.

Your sample date values require some preparation to yield the desired format. As your input data varies, you may need to modify the regular expression to allow strtotime() to properly handle the date expression.

Code: (Demo)

$html = <<<HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>

<table class="table-list table table-responsive table-striped" border="1">
<thead>
<tr>
<th class="coll-1 name">name</th>
<th class="coll-2">height</th>
<th class="coll-3">weight</th>
<th class="coll-date">date</th>
<th class="coll-4"><span class="info">info</span></th>
<th class="coll-5">country</th>
</tr>
</thead>
<tbody>
<tr>
<td class="coll-1 name">
<a href="/username/Jhon Doe/" class="icon"><i class="flaticon-user"></i></a>
<a href="/username/Jhon Doe/">Jhon Doe</a>
</td>
<td class="coll-2 height">45</td>
<td class="coll-3 weight">50</td>
<td class="coll-date">9am May. 16th</td>
<td class="coll-4 size mob-info">abcd</td>
<td class="coll-5 country"><a href="/country/CA/">CA</a></td>
</tr>
<tr>
<td class="coll-1 name">


Related Topics



Leave a reply



Submit