Jim*_*mmy 20 html jquery json html-table
任何人都知道如何将HTML值表转换为一个好的JSON对象,以便使用jQuery进行操作?
Poi*_*nty 33
一张HTML表格?比如,<td>二维数组中的所有内容?
var tbl = $('table#whatever tr').map(function() {
return $(this).find('td').map(function() {
return $(this).html();
}).get();
}).get();
Run Code Online (Sandbox Code Playgroud)
然后只需使用$ .json(或任何你想要的库)将其转换为JSON字符串.
编辑 - 重写以使用数组原型中的native(shim here).map():
var tbl = $('table#whatever tr').get().map(function(row) {
return $(row).find('td').get().map(function(cell) {
return $(cell).html();
});
});
Run Code Online (Sandbox Code Playgroud)
jQuery .map()函数具有将返回的数组展平为结果数组的"特性".也就是说,如果回调函数返回一个本身就是数组的值,那么它的元素将被添加到结果中,而不是返回的数组成为结果的一个单元格的值.map().
它可能会使用原始的jQuery版本,只是在返回的值周围包含一个额外的数组.
Joh*_*pel 21
你的意思是以下情况吗?
鉴于:
A1 B1 C1 ...
A2 B2 C2 ...
...
Run Code Online (Sandbox Code Playgroud)
需要:
{"1": ["A1", "B1", "C1", ...],
"2": ["A2", "B2", "C2", ...], ...}
Run Code Online (Sandbox Code Playgroud)
所以使用以下函数创建一个有效的JSON-String函数而不用尾随",":
function html2json() {
var json = '{';
var otArr = [];
var tbl2 = $('#dest_table tr').each(function(i) {
x = $(this).children();
var itArr = [];
x.each(function() {
itArr.push('"' + $(this).text() + '"');
});
otArr.push('"' + i + '": [' + itArr.join(',') + ']');
})
json += otArr.join(",") + '}'
return json;
}
Run Code Online (Sandbox Code Playgroud)
lig*_*h05 16
我需要相同的东西,除了能够忽略列,覆盖值,而不是被嵌套表混淆.我最终写了一个jQuery插件table-to-json:
https://github.com/lightswitch05/table-to-json
您所要做的就是使用jQuery选择表并调用插件:
var table = $('#example-table').tableToJSON();
Run Code Online (Sandbox Code Playgroud)
以下是它的实际演示:
http://jsfiddle.net/Crw2C/173/