【问题标题】:convert JSON with html table tag using JavaScript使用 JavaScript 将带有 html 表格标签的 JSON 转换
【发布时间】:2019-07-21 11:02:23
【问题描述】:

我正在尝试转换以表格形式出现的 SQL 查询的输出。我已将表格转换为 JSON。现在我正在将 JSON 转换为 HTML 表格,以便我可以将其用于报告。

脚本如下,

var value = '{"root":{"row":[{"DatabaseID":"21","fileid":"1","databaseName":"AutomationPortal","FileLogicalName":"AutomationPortal","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomationPortal.mdf","FileSizeMB":"100.00","SpaceUsedMB":"10.25","MaxfileSizeMB":"-0.01","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"},{"DatabaseID":"21","fileid":"3","databaseName":"AutomationPortal","FileLogicalName":"AutomatioPortal_01","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomatioPortal_01.ndf","FileSizeMB":"100.00","SpaceUsedMB":"0.06","MaxfileSizeMB":"130.00","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"}]}}'
        var data = JSON.parse(value);
        
        var tablearray = [];
        tablearray.push("<table><tr>")
        var queryRow = data.root.row.length;
        
        var headerProperty = Object.keys(data.root.row[0]);
        
        for (i=0;i<headerProperty.length;i++){
            tablearray.push("<th>"+headerProperty[i]+"</th>");
        }
        tablearray.push("</tr>");
        //console.log(tablearray);
        for (i=0;i<queryRow;i++){
            tablearray.push("<tr>")
            for (j=0;j<headerProperty.length;j++){
                // console.log(headerProperty[j]);
                // console.log(data.root.row[0].DatabaseID);
                // console.log(data.root.row[i].headerProperty[j]);
        tablearray.push("<td>"+data.root.row[i].headerProperty[j]+"</td>");
            }
            tablearray.push("</tr>");
        }
        tablearray.push("</table>");
        tablearray.join('');

当我运行上面的脚本时,它给了我以下错误,我无法解决这个问题。

tablearray.push(""+data.root.row[i].headerProperty[j]+""); ^

TypeError:无法读取未定义的属性“0” 在对象。 (C:\Users\convertjsontohtml.js:21:55) 在 Module._compile (internal/modules/cjs/loader.js:678:30) 在 Object.Module._extensions..js (internal/modules/cjs/loader.js:689:10) 在 Module.load (internal/modules/cjs/loader.js:589:32) 在 tryModuleLoad (internal/modules/cjs/loader.js:528:12) 在 Function.Module._load (internal/modules/cjs/loader.js:520:3) 在 Function.Module.runMain (internal/modules/cjs/loader.js:719:10) 启动时(内部/bootstrap/node.js:228:19) 在 bootstrapNodeJSCore (internal/bootstrap/node.js:575:3)

我期望的输出类似于“”

【问题讨论】:

    标签: javascript html json


    【解决方案1】:

    data.root.row[0] 内没有可用的 headerProperty

    【讨论】:

      【解决方案2】:

      您可以通过循环思考每个值来构建表格,如下所示:

      const input = '{"root":{"row":[{"DatabaseID":"21","fileid":"1","databaseName":"AutomationPortal","FileLogicalName":"AutomationPortal","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomationPortal.mdf","FileSizeMB":"100.00","SpaceUsedMB":"10.25","MaxfileSizeMB":"-0.01","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"},{"DatabaseID":"21","fileid":"3","databaseName":"AutomationPortal","FileLogicalName":"AutomatioPortal_01","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomatioPortal_01.ndf","FileSizeMB":"100.00","SpaceUsedMB":"0.06","MaxfileSizeMB":"130.00","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"}]}}';
      
      // Parse given JSON
      const parsed = JSON.parse(input);
      
      // Get keys (=cells) of each items
      const keys = Object.keys(parsed.root.row[0]);
      
      // Build the table header
      const header = `<thead><tr>` + keys
        .map(key => `<th>${key}</th>`)
        .join('') + `</thead></tr>`;
        
      // Build the table body
      const body = `<tbody>` + parsed.root.row
        .map(row => `<tr>${Object.values(row)
          .map(cell => `<td>${cell}</td>`)
          .join('')}</tr>`
        ).join('');
        
      // Build the final table
      const table = `
      <table>
        ${header}
        ${body}
      </table>
      `;
        
      // Append the result into #root element
      document.getElementById('root').innerHTML = table;
      &lt;div id="root"&gt;&lt;/div&gt;

      【讨论】:

        【解决方案3】:

        您可能希望使用 document.createElement 创建元素,而不是使用字符串

        const value = '{"root":{"row":[{"DatabaseID":"21","fileid":"1","databaseName":"AutomationPortal","FileLogicalName":"AutomationPortal","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomationPortal.mdf","FileSizeMB":"100.00","SpaceUsedMB":"10.25","MaxfileSizeMB":"-0.01","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"},{"DatabaseID":"21","fileid":"3","databaseName":"AutomationPortal","FileLogicalName":"AutomatioPortal_01","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomatioPortal_01.ndf","FileSizeMB":"100.00","SpaceUsedMB":"0.06","MaxfileSizeMB":"130.00","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"}]}}'
        const data = JSON.parse(value);
        console.log(data);
        
        const $table = document.createElement('table');
        const $head = document.createElement('thead');
        const $body = document.createElement('tbody');
        
        for (let i = 0; i < data.root.row.length; i++) {
          const $tr = document.createElement('tr');
        
          Object.keys(data.root.row[0]).forEach((colName) => {
            if (i === 0) {
              const $th = document.createElement('th');
              $th.innerText = colName;
              $head.appendChild($th);
            }
            const $td = document.createElement('td');
            $td.innerText = data.root.row[0][colName];
            $tr.appendChild($td);
          });
        
          $body.appendChild($tr);
        }
        
        $table.appendChild($head);
        $table.appendChild($body);
        
        document.getElementById('table').appendChild($table);
        &lt;div id="table"&gt;&lt;/div&gt;

        【讨论】:

          【解决方案4】:

          问题是您的rows 没有名为“headerProperty”的属性。我认为您想使用 headerProperty[j] 中的 value 作为动态属性名称?

          为此,您必须使用“括号表示法”来编写属性访问器 - 这允许您在运行时使用任何字符串值作为属性名称:

          data.root.row[i][propertyHeader[j]]
          

          更多信息请参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors

          演示 - 我希望现在可以输出您所期望的结果:

          var value = '{"root":{"row":[{"DatabaseID":"21","fileid":"1","databaseName":"AutomationPortal","FileLogicalName":"AutomationPortal","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomationPortal.mdf","FileSizeMB":"100.00","SpaceUsedMB":"10.25","MaxfileSizeMB":"-0.01","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"},{"DatabaseID":"21","fileid":"3","databaseName":"AutomationPortal","FileLogicalName":"AutomatioPortal_01","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomatioPortal_01.ndf","FileSizeMB":"100.00","SpaceUsedMB":"0.06","MaxfileSizeMB":"130.00","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"}]}}'
          var data = JSON.parse(value);
          
          var tablearray = [];
          tablearray.push("<table><tr>")
          var queryRow = data.root.row.length;
          
          var headerProperty = Object.keys(data.root.row[0]);
          
          for (i = 0; i < headerProperty.length; i++) {
            tablearray.push("<th>" + headerProperty[i] + "</th>");
          }
          tablearray.push("</tr>");
          //console.log(tablearray);
          
          for (i = 0; i < queryRow; i++) {
            tablearray.push("<tr>")
            for (j = 0; j < headerProperty.length; j++) {
              // console.log(headerProperty[j]);
              // console.log(data.root.row[0].DatabaseID);
              // console.log(data.root.row[i].headerProperty[j]);
              tablearray.push("<td>" + data.root.row[i][headerProperty[j]] + "</td>");
            }
            tablearray.push("</tr>");
          }
          tablearray.push("</table>");
          document.write(tablearray.join(''));

          【讨论】:

            【解决方案5】:

            这是我转换任何 json(包含对象添加/或列表)的通用代码。构建这样的表格可以用来可视化我们的 json,有时甚至可以在生产代码中使用它来支持调试。

            const getType = obj => Object.prototype.toString.call(obj).slice(8, -1);
            const isArray = obj => getType(obj) === 'Array';
            const isMap = obj => getType(obj) === 'Object';
            var buildList = function(data) {
              const keys = new Set();
              var str = "<table border==\"0\"><tr>";
              for (var i = 0; i < data.length; i++) {
                for (key in data[i]) {
                  keys.add(key);
                }
              }
              for (key of keys) {
                str = str.concat('<td>' + key + '</td>');
              }
              str = str.concat("</tr>");
              for (var i = 0; i < data.length; i++) {
                str = str.concat('<tr>');
                for (key of keys) {
                  str = str.concat('<td>');
                  if (data[i][key]) {
                    if (isMap(data[i][key])) {
                      str = str.concat(buildMap(data[i][key]));
                    } else if (isArray(data[i][key])) {
                      str = str.concat(buildList(data[i][key]));
                    } else {
                      str = str.concat(data[i][key]);
                    }
                  }
                  str = str.concat('</td>');
                }
                str = str.concat('</tr>');
              }
              str = str.concat("</table>");
              return str;
            }
            var buildMap = function(data) {
              var str = "<table border==\"0\">";
              for (const key in data) {
                str = str.concat('<tr><td>' + key + '</td><td>');
                if (isArray(data[key])) {
                  str = str.concat(buildList(data[key]));
                } else if (isMap(data[key])) {
                  str = str.concat(buildMap(data[key]));
                } else {
                  str = str.concat(data[key]);
                }
                str = str.concat('</td></tr>');
              }
              str = str.concat("</table>");
              return str;
            }
            
            var value = '{"root":{"row":[{"DatabaseID":"21","fileid":"1","databaseName":"AutomationPortal","FileLogicalName":"AutomationPortal","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomationPortal.mdf","FileSizeMB":"100.00","SpaceUsedMB":"10.25","MaxfileSizeMB":"-0.01","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"},{"DatabaseID":"21","fileid":"3","databaseName":"AutomationPortal","FileLogicalName":"AutomatioPortal_01","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomatioPortal_01.ndf","FileSizeMB":"100.00","SpaceUsedMB":"0.06","MaxfileSizeMB":"130.00","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"}]}}';
            var data = JSON.parse(value);
            var outHtml = "No Data found";
            if (isArray(data)) {
              outHtml = buildList(data);
            } else if (isMap(data)) {
              outHtml = buildMap(data);
            }
            document.getElementById("main").innerHTML = outHtml;</script>
            &lt;div id="main"&gt;&lt;/div&gt;

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2020-05-14
              • 2016-06-12
              • 2019-05-07
              • 1970-01-01
              • 2022-01-13
              • 1970-01-01
              • 2014-11-23
              • 2019-09-25
              相关资源
              最近更新 更多