通过忽略特定列将HTML表数据转换为jQuery中的JSON对象

时间:2019-05-01 05:09:19

标签: javascript jquery json object

通过忽略特定列的值将HTML值表转换为JSON对象以供jQuery操作

例如: 我有一张桌子,

fstname lastName    Age
john    gobby   8
Adams   mekander    10
jimmy   Rumpel  11

我需要下面提到的json结果

我的代码如下,

$(document).ready(function () {
            $("#ConvertJsonButton").click(function () {
                var myRows = [];
                var headers = [];
$("#tablesort tr#datajson").each(function(index) {
    if (index === 0) {
                //for headers
                   $cells = $(this).find("td.cellClass");
                    headers[index] = {};                 
    $cells.each(function (cellIndex) {                                  
    headers[cellIndex] = $(this).text();                                                    
                 });
    }               
    else {                      
                $cells = $(this).find("td.cellClass");
        myRows[index] = {};
    $cells.each(function (cellIndex) {                                                  
        myRows[index][headers[cellIndex]] = $(this).text();
            });                     
                    }
    });             
        var myObj = {};
        myObj.myrows = myRows;              
        alert(JSON.stringify(myObj));               
            });
        });

我想要这个结果:

{
  "john": {
    "lastName": "gobby",
    "Age": "8"
  },
  "Adams": {
    "lastName": "Mekander",
    "Age": "10"
  },
  "jimmy": {
    "lastName": "Rumpel",
    "Age": "11" 
  },
}

1 个答案:

答案 0 :(得分:1)

使用jquery.tabletojson.min.js

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.github.developerdan.com/table-to-json/javascripts/jquery.tabletojson.min.js"></script>
<script>
$(document).ready(function(){
  $('#run').click( function() {
    var table = $('#example-table').tableToJSON();
    var data = {};
    $.each(table, function(key, value) {
        var jsonKey = value.firstname;
        var map = {};
        map = value;
        map.firstname = undefined;
        data[jsonKey] = map;
    }); 
    alert(JSON.stringify(data));
    console.log(JSON.stringify(data));
});
});
</script>
</head>
<body>

<table id="example-table" class="table table-striped" border="1">
   <thead>
      <tr>
         <th>firstname</th>
         <th>lastname</th>
         <th>age</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td>john</td>
         <td>goby</td>
         <td>8</td>
      </tr>
      <tr>
         <td>Adams</td>
         <td>mekander</td>
         <td>10</td>
      </tr>
      <tr>
         <td>jimmy</td>
         <td>Rumpel</td>
         <td>11</td>
      </tr>
   </tbody>
</table>
<button id="run" class="btn btn-primary">Convert!</button>

</body>
</html>