1

How can I transform html table into JSON String.

example :

<table cellpadding="0" cellspacing="0"> <tbody> <tr> <td>Car</td> <td>Year</td> </tr> <tr> <td>Nissan</td> <td>2009</td> </tr> <tr> <td>Chrysler</td> <td>2004</td> </tr> </tbody> </table> 

Something like: $('table tr').toJSON to print out all value of td

0

6 Answers 6

4

Try this

 var rowList = new Array(); $("table tr").each(function () { var colList = new Array(); $("td", this).each(function () { colList.push($(this).text()); }); rowList.push(colList); }); 

The rowList is the 2 dimensional list of all the values in td's

Sign up to request clarification or add additional context in comments.

Comments

1

Make sure that you have id associated with table and then you can convert all the td content into an array of array (i mean two dimensional array)

 var tableData = $('table#yourId tr').map(function() { return $(this).find('td').map(function() { return $(this).html(); }).get(); }).get(); 

Now tableData will have all the tds data in it.

Comments

1

Get the table data in an array using $('table tr').find('td').each()

This use the JSON.stringify function to make it a string.

JSON.stringify(carsArray)

Comments

1

I was unhappy with all the solutions above and ended up writing my own jQuery plugin to accomplish this. It is very similar to the solution but accepts several options to customize the results, such as ignoring hidden rows, overriding column names, and overriding cell values

The plugin can be found here along with some examples if this is more what your looking for: https://github.com/lightswitch05/table-to-json

Comments

1

Try this one.. do a firebug and see the JSON result.. in here you will specify the values of your selectors. Change the selectors accordingly to your needs

 function TableDataToJSON() { var list= []; var $headers = $("#list> thead >tr >th"); //header selector var $rows = $('#list> .trClass').each(function (index) {//row selector $cells = $(this).find("td"); list[index] = {}; $cells.each(function (cellIndex) { list[index][$($headers[cellIndex]).attr('id')] = $(this).text(); }); }); var myObj = {}; myObj.person= list; return JSON.stringify(myObj); //this one $($headers[cellIndex]).attr('id') will give a property name to your //json values e.g {Firstname: 'John'} } 

Comments

0

I am not sure about the codding solution but there is a one java-Script lib available please try this

The fastfrag json will convert all html in to json format. Just copy you code in the text area and click on link below. It also has code repository on github

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.