Click here to Skip to main content
15,905,913 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a table from which i would like to iterate over and create json data. 
	I would like to get properties from column head and value from tbody td.
I would like to get myContact = [{Name = "Mary Jane", Gender= "female"},{Name = "Peter Parker", Gender= "male"}]


HTML
<pre><table>
<thead>
<tr><td>Name</td><td>Gender</td></tr>
</thead>
<tbody>
<tr><td>Mary Jane</td><td>female</td></tr>
<tr><td>Peter Parker</td><td>Male</td></tr>
</tbody>
</table>


What I have tried:

I only able to create Array of Array object.

$('#myButton').on('click', function () {
            var table = $('#myTable');
            var data = getTableData(table);
            console.log(data);

            $.ajax({
                url: "/home/DownloadContacts",
                method: "get",
                data: { "list": data , "type":1}
            }).done(function (response) {
                console.log(response.data);
            });
        });

        function getTableData(table) {
            var data = [];
            var target = $('tr').not('thead tr');
            //table.find('tr').each(function (rowIndex, r) {
            target.each(function (rowIndex, r) {
                var cols = [];
                $(this).find('th,td').each(function (colIndex, c) {
                    cols.push(c.textContent);
                });
                data.push(cols);
            });
            return data;
        }
Posted
Updated 25-Sep-18 4:06am

1 solution

This should get you what you need:

<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function CreateJson() {
	
	var myRows = [];
	var $headers = $("thead tr").find("td"); 
	var $rows = $("tbody tr").each(function(index) {
	  $cells = $(this).find("td");
	  myRows[index] = {};
	  $cells.each(function(cellIndex) {
		myRows[index][$($headers[cellIndex]).html()] = $(this).html();
	  });    
	});

	// Put this an object to convert to JSON
	var myObj = {};
	myObj.myrows = myRows;
	alert(JSON.stringify(myObj));
}

    $().ready(function() {

		$("#btnTableToJson").click(function() {
            CreateJson();
        });
    });
</script>
<style>
</style>
<html>


<body>
<table id="myTable">
<thead>
<tr><td>Name</td><td>Gender</td></tr>
</thead>
<tbody>
<tr><td>Mary Jane</td><td>female</td></tr>
<tr><td>Peter Parker</td><td>Male</td></tr>
</tbody>
</table>
<input id="btnTableToJson" type="button" value="To JSON" />
</body>
</html>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900