如何使用解析的JSON使用Javascript转换为html表

时间:2019-02-12 08:00:05

标签: javascript html arrays json

我不想在一行中打印出员工信息,而是要使用变量“ obj”来创建一个HTML表(如果有所有员工信息)。但是,我无法传递“ obj”。请指教。

var text = '{"employees":[' + '{"Name":"Tony","Mobile":"99221111","Email":"tony@json.com" },' + '{"Name":"Linda","Mobile":"98981111","Email":"linda@json.com" },' + '{"Name":"Patrick","Email":"patrick@json.com" },' + '{"Name":"Isabella","Mobile":"99552222" }]}'; 
obj = JSON.parse(text);

function buildHtmlTable(selector) {
  var columns = addAllColumnHeaders(obj, selector);

  for (var i = 0; i < obj.length; i++) {
    var row$ = $('<tr/>');
    for (var colIndex = 0; colIndex < columns.length; colIndex++) {
      var cellValue = obj[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(obj, selector) {
  var columnSet = [];
  var headerTr$ = $('<tr/>');

  for (var i = 0; i < obj.length; i++) {
    var rowHash = obj[i];
    for (var key in rowHash) {
      if ($.inArray(key, columnSet) == -1) {
        columnSet.push(key);
        headerTr$.append($('<th/>').html(key));
      }
    }
  }
  $(selector).append(headerTr$);
<!DOCTYPE html>
<html>
<head>
	<title>Task 1</title>
</head>
<body onLoad="buildHtmlTable('#excelDataTable')">
  <table id="excelDataTable" border="1">
  </table>
	<p id="demo"></p>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<script src = "Task1ab.js"></script>
</body>
</html>

3 个答案:

答案 0 :(得分:0)

请点击以下链接:https://www.encodedna.com/javascript/populate-json-data-to-html-table-using-javascript.htm

<!DOCTYPE html>
    <html>
    <head>
        <title>Example</title>
        <style>
            th, td, p, input {
                font:14px;
            }
            table, th, td 
            {
                border: solid 1px #DDD;
                border-collapse: collapse;
            }
            th {
                font-weight:bold;
            }
        </style>
    </head>
    <body>
        <input type="button" onclick="CreateTable()" value="Create Table From JSON" />
        <p id="showData"></p>
    </body>

    <script>
        function CreateTable() {
            var employees = [
        {
          "Name": "Tony",
          "Mobile": "99221111",
          "Email": "tony@json.com"
        },
        {
          "Name": "Linda",
          "Mobile": "98981111",
          "Email": "linda@json.com"
        },
        {
          "Name": "Patrick",
          "Email": "patrick@json.com"
        },
        {
          "Name": "Isabella",
          "Mobile": "99552222"
        }
      ]

            // EXTRACT VALUE FOR HTML HEADER. 
            var col = [];
            for (var i = 0; i < employees.length; i++) {
                for (var key in employees[i]) {
                    if (col.indexOf(key) === -1) {
                        col.push(key);
                    }
                }
            }

            // CREATE DYNAMIC TABLE.
            var table = document.createElement("table");

            // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

            var tr = table.insertRow(-1);                   // TABLE ROW.

            for (var i = 0; i < col.length; i++) {
                var th = document.createElement("th");      // TABLE HEADER.
                th.innerHTML = col[i];
                tr.appendChild(th);
            }

            // ADD JSON DATA TO THE TABLE AS ROWS.
            for (var i = 0; i < employees.length; i++) {

                tr = table.insertRow(-1);

                for (var j = 0; j < col.length; j++) {
                    var tabCell = tr.insertCell(-1);
                    tabCell.innerHTML = employees[i][col[j]] ? employees[i][col[j]] : 'NA';
                }
            }

            // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
            var divContainer = document.getElementById("showData");
            divContainer.innerHTML = "";
            divContainer.appendChild(table);
        }
    </script>
    </html>

答案 1 :(得分:0)

包装json字段非常简单。

有足够的库也可以这样做。

您也可以使用jput jQuery插件或json2html

var transform = {"tag":"table", "children":[
    {"tag":"tbody","children":[
        {"tag":"tr","children":[
            {"tag":"td","html":"${name}"},
            {"tag":"td","html":"${age}"}
        ]}
    ]}
]};

var data = [
    {'name':'Bob','age':40},
    {'name':'Frank','age':15},
    {'name':'Bill','age':65},
    {'name':'Robert','age':24}
];

请参见this答案

$('#target_div').html(json2html.transform(data,transform));

答案 2 :(得分:0)

更改1:您将 obj 称为Array。但是实际的数组是对象内部的雇员。所以obj = JSON.parse(text).employees;是我们需要迭代的

更改2:var columns = addAllColumnHeaders(obj, selector);期望返回值。但是函数 addAllColumnHeaders 不返回任何内容。因此,请在函数中添加return语句return columnSet;

修改后的js代码如下

var text = '{"employees":[' + '{"Name":"Tony","Mobile":"99221111","Email":"tony@json.com" },' + '{"Name":"Linda","Mobile":"98981111","Email":"linda@json.com" },' + '{"Name":"Patrick","Email":"patrick@json.com" },' + '{"Name":"Isabella","Mobile":"99552222" }]}'; 
obj = JSON.parse(text).employees;

function buildHtmlTable(selector) {
  var columns = addAllColumnHeaders(obj, selector);

  for (var i = 0; i < obj.length; i++) {
    var row$ = $('<tr/>');
    for (var colIndex = 0; colIndex < columns.length; colIndex++) {
      var cellValue = obj[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(obj, selector) {
  var columnSet = [];
  var headerTr$ = $('<tr/>');

  for (var i = 0; i < obj.length; i++) {
    var rowHash = obj[i];
    for (var key in rowHash) {
      if ($.inArray(key, columnSet) == -1) {
        columnSet.push(key);
        headerTr$.append($('<th/>').html(key));
      }
    }
  }
  $(selector).append(headerTr$);
  return columnSet;

  }

希望这会有所帮助。谢谢