使用Javscript将html表标记转换为JSON

时间:2019-02-27 16:37:52

标签: javascript html json

我正在尝试将SQL Query的输出转换为表格。我已将表转换为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(内部/模块/cjs/loader.js:678:30)       在Object.Module._extensions..js(内部/模块/cjs/loader.js:689:10)       在Module.load(internal / modules / cjs / loader.js:589:32)       在tryModuleLoad(内部/模块/cjs/loader.js:528:12)       在Function.Module._load(内部/模块/cjs/loader.js:520:3)       在Function.Module.runMain(内部/模块/cjs/loader.js:719:10)       在启动时(internal / bootstrap / node.js:228:19)       在bootstrapNodeJSCore(internal / bootstrap / node.js:575:3)

我期望的输出像“”

4 个答案:

答案 0 :(得分:3)

您可以像这样循环每个值来构建表:

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;
<div id="root"></div>

答案 1 :(得分:2)

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

答案 2 :(得分:1)

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

javax.json:javax.json-api
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);

答案 3 :(得分:1)

问题是您的class Person(name: String, age: Integer) { def getAge(): Integer = { age } def getName(): String = { name } } object Person { def create(name: String, age: Integer) { new Person(name, age) } val species = "homoSapiens" } object mainMethod { def main(args: Array[String]): Unit = { // this is what I want to make work val person = Person.create("Sarah", 18) println(person.species) } } 没有一个名为“ headerProperty”的属性。我认为您想将row内的 value 用作动态属性名称?

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

headerProperty[j]

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

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

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