如何用javascript把下表转换成JSON?

chhkpiq4  于 2023-01-29  发布在  Java
关注(0)|答案(7)|浏览(323)

如何在jquery/javascript中把下面的表做成JSON字符串?

<table>
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>A1</td>
      <td>A2</td>
      <td>A3</td>
    </tr>
    <tr>
      <td>B1</td>
      <td>B2</td>
      <td>B3</td>
    </tr>
    <tr>
      <td>C1</td>
      <td>C2</td>
      <td>C3</td>
    </tr>
  </tbody>
</table>

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

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

实现此目标的最佳方法是什么?(注意:可能有不同数量的行,我只想提取文本,同时忽略表中的其他标记)

mfuanj7w

mfuanj7w1#

**更新:**有一个slightly improved fork of the solution (below) on 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"}]}
cgh8pdjw

cgh8pdjw2#

下面是一个受this article启发的不使用jQuery的解决方案:

function tableToJson(table) { 
    var data = [];
    for (var i = 1; i < table.rows.length; i++) { 
        var tableRow = table.rows[i]; 
        var rowData = []; 
        for (var j = 0; j < tableRow.cells.length; j++) { 
            rowData.push(tableRow.cells[j].innerHTML);
        } 
        data.push(rowData); 
    } 
    return data; 
}
azpvetkf

azpvetkf3#

我需要同样的东西,除了能够忽略列、覆盖值和不被嵌套表混淆。我最终编写了一个jQuery插件table-to-json:
https://github.com/lightswitch05/table-to-json
您所要做的就是使用jQuery选择表并调用插件:

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

下面是它的实际演示:
http://jsfiddle.net/nyg4z/27/

hzbexzde

hzbexzde4#

我的版本是:

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

请参见Fiddle

piok6c0g

piok6c0g5#

试试这个。

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/

pgpifvop

pgpifvop6#

var _table = document.getElementById("table");
var _trLength = _table.getElementsByTagName("tr").length;
var _jsonData = [];
var _obj = {};

var _htmlToJSON = function(index){
    var _tr = _table.getElementsByTagName("tr")[index];
    var _td = _tr.getElementsByTagName("td");
    var _arr = [].map.call( _td, function( td ) {
        return td.innerHTML;
    }).join( ',' );
    var _data = _arr.split(",");
    
    _obj = {
         column1     : _data[0]
        ,column2     : _data[1]
        ,column3     : _data[2]
    };
    
    _jsonData.push(_obj);
    
};

for(var i = 1; i < _trLength; i++){
    _htmlToJSON(i);
}
console.log("html to JSON",_jsonData);
mqkwyuun

mqkwyuun7#

给你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));

相关问题