javascript - 使用 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
}
]
解决方案
此脚本为您创建简单的 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);
推荐阅读
- go - 有没有办法在 context.Context 中列出键?
- javascript - React - 向组件发送道具
- vue.js - vue 反应性问题:禁用
- node.js - 如何过滤具有日期范围的 web3 事件?
- c# - C# WPF 形状旋转锯齿状边缘
- twilio - 使用 GATHER 在 Twilio 中收集用户名
- windows - 未知的 Objective-C 运行时“微软”
- javascript -
静态资源忽略Angular - dji-sdk - 'DJI.WindowsSDK.DJISDKManager' 抛出异常
- android - Kotlin:EditText 在 afterTextChanged() 中为空