如何使用javascript将下表转换为JSON?

如何将下表变成jquery / javascript中的JSON字符串?

Column 1 Column 2 Column 3
A1 A2 A3
B1 B2 B3
C1 C2 C3

我想这样做,我可以在变量“myjson”中获得一个可以在POST请求或GET请求中使用的JSON字符串:

 { "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" } ] } 

完成此任务的最佳方法是什么? (注意:可能存在不同数量的行,我只想提取文本而忽略表中的其他标记)

更新: 在jsFiddle上有一个稍微改进的解决方案(下面) 。

你只需要把你的桌子的DOM读出来……这甚至没有接近优化,但会给你你想要的结果。 ( 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));​ 

而输出……

 {"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"}]} 

试试这个。

 var myRows = { myRows: [] }; var $th = $('table th'); $('table tbody tr').each(function(i, tr){ var obj = {}, $tds = $(tr).find('td'); $th.each(function(index, th){ obj[$(th).text()] = $tds.eq(index).text(); }); myRows.myRows.push(obj); }); alert(JSON.stringify(myRows)); 

工作演示 – http://jsfiddle.net/u7nKF/1/

我的版本:

 var $table = $("table"), rows = [], header = []; $table.find("thead th").each(function () { header.push($(this).html()); }); $table.find("tbody tr").each(function () { var row = {}; $(this).find("td").each(function (i) { var key = header[i], value = $(this).html(); row[key] = value; }); rows.push(row); }); 

看小提琴 。

我需要相同的东西,除了能够忽略列,覆盖值,而不是被嵌套表混淆。 我最终写了一个jQuery插件table-to-json:

https://github.com/lightswitch05/table-to-json

您所要做的就是使用jQuery选择表并调用插件:

 var table = $('#example-table').tableToJSON(); 

以下是它的实际演示:

http://jsfiddle.net/nyg4z/27/

在这里你去http://jsfiddle.net/Ka89Q/4/

 var head = [], i = 0, tableObj = {myrows: []}; $.each($("#my_table thead th"), function() { head[i++] = $(this).text(); }); $.each($("#my_table tbody tr"), function() { var $row = $(this), rowObj = {}; i = 0; $.each($("td", $row), function() { var $col = $(this); rowObj[head[i]] = $col.text(); i++; }) tableObj.myrows.push(rowObj); }); alert(JSON.stringify(tableObj));