javascript 从 html 表创建一个 json 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5917647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:47:21  来源:igfitidea点击:

create a json array from html table

javascriptjson

提问by Ali1S232

i have C++ program exporting log files as HTML table and I wanted to know if there is any way that i can parse that table(something like this):

我有 C++ 程序将日志文件导出为 HTML 表,我想知道是否有任何方法可以解析该表(类似这样):

<table>
<tr><td>id</td><td>value1</td><td>value2</td></tr>
<tr><td>0 </td><td>0     </td><td>0     </td></tr>
<tr><td>0 </td><td>1.5   </td><td>2.15  </td></tr>
</table>

into a JSON array (something like this) using a Javascript function:

使用 Javascript 函数转换成一个 JSON 数组(类似这样):

 var chartData = [
            {id:"0",value1:"0",value2:"0"},
            {id:"1",value1:"1.5",value2:"2.15"}];

The problem is that I want this function to work for every table given to it, with any possible row or column count(first row is always a header).

问题是我希望这个函数适用于给它的每个表,任何可能的行或列数(第一行总是一个标题)。

采纳答案by mVChr

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 →

参见工作示例 →

回答by Felix Kling

Something like this, assuming the first row is always the header (could certainly be changed to make it more flexible):

像这样,假设第一行始终是标题(当然可以更改以使其更灵活):

function getData(table, format) {
    var rows = table.tBodies[0].rows,
        header_row = rows[0],
        result = [],
        header = [],
        format = format || function(val){return val;},
        i, j, cell, row, row_data;

    // extract header
    for(i = 0, l = header_row.cells.length; i < l; i++) {
        cell = header_row.cells[i];
        header.push((cell.textContent || cell.innerText));
    }

    // extract values
    for(i = 1, l = rows.length; i < l; i++) {
        row = rows[i];
        row_data = {};
        for(j = 0, l = row.cells.length; j < l; j++) {
            cell = row.cells[j];
            row_data[header[j]] = format(i, j, cell.textContent || cell.innerText);
        }
        result.push(row_data);
    }
    return result;
}

Usage is:

用法是:

var chartData = getData(referenceToTable, function(rowIndex, colIndex, value) {
    return +value; // shortcut to format text to a number
});

By passing a format function, you can format the values of each cell into the right data type.

通过传递格式函数,您可以将每个单元格的值格式化为正确的数据类型。

DEMO

演示

It works under the assumption that there is only one tbodyelement. You have to adjust it to your needs.

它在只有一个tbody元素的假设下工作。您必须根据自己的需要进行调整。

回答by Edgar Villegas Alvarado

You could do it using the jquery framework. I

您可以使用 jquery 框架来做到这一点。一世

<sript src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
  var chartData = [];
  $("table tr").each(function(i){
    if(i==0) return;
    var id = $.trim($(this).find("td").eq(0).html());
    var value1 = $.trim($(this).find("td").eq(1).html());
    var value2 = $.trim($(this).find("td").eq(2).html());
    chartData.push({id: id, value1: value1, value2: value2});
  });
//now you have the chartData array filled
});
</script>

Cheers.

干杯。

回答by lightswitch05

I needed the same thing except with the ability to ignore columns, override values, and not be confused by nested tables. I ended up writing a jQuery plugin table-to-json:

除了能够忽略列、覆盖值和不被嵌套表混淆之外,我需要同样的东西。我最终编写了一个 jQuery 插件table-to-json

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

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

All you have to do is select your table using jQuery and call the plugin:

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

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

Here is a demo of it in action using your data:

这是使用您的数据进行操作的演示:

http://jsfiddle.net/dGPks/199/

http://jsfiddle.net/dGPks/199/

回答by Jacob

Since that table format looks like well-formed XML, I'd use XSLT to make the conversion; your C++ program could then just invoke an XSLT engine.

由于该表格式看起来像格式良好的 XML,我将使用 XSLT 进行转换;然后您的 C++ 程序就可以调用 XSLT 引擎。