首页 > 解决方案 > 使用 nodejs 从 json 生成 .html 文件

问题描述

我正在使用 Node.js 进行自动化工作,我有 JSON 数据,我想在每个间隔后从它们生成 html 文件。例如,我有一个从数据库中检索所有 JSON 数据的函数,现在我希望它自动生成 .html 文件到给定 JSON 数据的路径。我该如何处理?是否有任何节点库或任何示例可以做到这一点?这是我的json:

[
 {
    id: '5ffee71aef57d4cf197729a5',
    date_checked: '2021-02-11T07:56:39.042Z',
    title: 'Notification with API',
    status: 'created',
    reach: null,
    sent: null,
    delivered: null,
    views: null,
    clicks: null,
    unsubscribers: null
  },
  {
    id: '5ffee71aef57d4cf197729a5',
    date_checked: '2021-02-11T07:56:39.042Z',
    title: 'Notification with API',
    status: 'created',
    reach: null,
    sent: null,
    delivered: null,
    views: null,
    clicks: null,
    unsubscribers: null
  }
]

标签: javascripthtmlnode.js

解决方案


此脚本为您创建简单的 html json 您可以扩展列数组以添加您希望在表中的其他字段。

const fs = require('fs')
const columns = [];
for (let name in json[0]){
  if(!json[0].hasOwnProperty(name)) continue;
  columns.push(name);
}

const html = '<html><body><table><thead><tr>';

for (let item of columns) {
  html += '<th>' + item + '</th>';
}

html += '</tr></thead><tbody>';

for (let item of json) {
  html += '<tr>';
  for (let name of columns) {
    html += '<td>' + item[name] +'</td>';
  }
  html += '</tr>';
}

html += '</tbody></table></body></html>';
file.writeFileSync(new Date().getTime().toString() + '.html', html);

推荐阅读