一尘不染

将json数据转换为html表

javascript

是否有任何jQuery或javascript库根据给定的json数据生成动态表?我不想定义列,该库应该读取json哈希中的键并生成列。

当然,我可以自己遍历json数据并生成html表。我只想知道是否存在可以简单重用的此类库。


阅读 361

收藏
2020-04-25

共1个答案

一尘不染

感谢大家的答复,这使用jQuery。

程式码片段:

var myList = [

  { "name": "abc", "age": 50 },

  { "age": "25", "hobby": "swimming" },

  { "name": "xyz", "hobby": "programming" }

];



// Builds the HTML Table out of myList.

function buildHtmlTable(selector) {

  var columns = addAllColumnHeaders(myList, selector);



  for (var i = 0; i < myList.length; i++) {

    var row$ = $('<tr/>');

    for (var colIndex = 0; colIndex < columns.length; colIndex++) {

      var cellValue = myList[i][columns[colIndex]];

      if (cellValue == null) cellValue = "";

      row$.append($('<td/>').html(cellValue));

    }

    $(selector).append(row$);

  }

}



// Adds a header row to the table and returns the set of columns.

// Need to do union of keys from all records as some records may not contain

// all records.

function addAllColumnHeaders(myList, selector) {

  var columnSet = [];

  var headerTr$ = $('<tr/>');



  for (var i = 0; i < myList.length; i++) {

    var rowHash = myList[i];

    for (var key in rowHash) {

      if ($.inArray(key, columnSet) == -1) {

        columnSet.push(key);

        headerTr$.append($('<th/>').html(key));

      }

    }

  }

  $(selector).append(headerTr$);



  return columnSet;

}


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>



<body onLoad="buildHtmlTable('#excelDataTable')">

  <table id="excelDataTable" border="1">

  </table>

</body>
2020-04-25