最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - create a json array from html table - Stack Overflow

programmeradmin6浏览0评论

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

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

Share Improve this question edited May 6, 2011 at 22:31 Ryan 28.2k10 gold badges58 silver badges83 bronze badges asked May 6, 2011 at 22:23 Ali1S232Ali1S232 3,4112 gold badges28 silver badges46 bronze badges 4
  • chartData is a normal JavaScript array, not JSON (something must be wrong today, so many people confusing this). – Felix Kling Commented May 6, 2011 at 22:26
  • anyway how can i extract data from table to array? – Ali1S232 Commented May 6, 2011 at 22:28
  • If you can use jquery, this should be an easy job. – morgar Commented May 6, 2011 at 22:28
  • 2 Interesting challenge to do without jQuery though... accepted! – mVChr Commented May 6, 2011 at 22:32
Add a ment  | 

5 Answers 5

Reset to default 5

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 →

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.

You could do it using the jquery framework. I

<sript src="http://code.jquery./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.

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./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/dGPks/199/

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.

发布评论

评论列表(0)

  1. 暂无评论