从 html 表创建一个 json 数组

发布于 2024-11-05 21:42:40 字数 640 浏览 0 评论 0原文

我有 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>

使用 Javascript 函数将该表(类似这样)解析为 JSON 数组(类似这样):

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

问题是我希望这个函数适用于给定的每个表,具有任何可能的行或列计数(第一行始终是标题)。

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):

<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:

 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).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

趁微风不噪 2024-11-12 21:42:40

这是我的实现:

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;
};

您可以像这样调用:

var obj = tableToObj( document.getElementsByTagName('table')[0] ); // or
var obj = tableToObj( document.getElementById('myTable') );

查看工作示例→

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 →

苏别ゝ 2024-11-12 21:42:40

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

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;
}

用法是:

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

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

DEMO

它的工作原理是假设只有一个tbody 元素。您必须根据您的需要进行调整。

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 tbody element. You have to adjust it to your needs.

蝶舞 2024-11-12 21:42:40

您可以使用 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>

干杯。

You could do it using the jquery framework. I

<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.

痞味浪人 2024-11-12 21:42:40

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

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

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

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

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

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

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:

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

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

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

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

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

缘字诀 2024-11-12 21:42:40

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文