javascript - 如何使用我自己的格式将 JSON 对象转换为 javascript 文件
问题描述
我有一个像这样的 json 对象
{
APP_NAME: "Test App",
APP_TITLE: "Hello World"
}
现在我想将其转换为 javascript 文件并下载该文件,文件格式应如下所示
// 配置.ts
export const APP_NAME: "Test App";
export const APP_TITLE: "Hello World";
解决方案
对于这种情况,您可以使用fs.createWriteStream()
将数据写入文件。循环 json 对象并附加内容。
选项 1:后端
// Initialize the file
var fs = require('fs')
var editor = fs.createWriteStream('config.ts')
const data = {
APP_NAME: "Test App",
APP_TITLE: "Hello World"
};
// Loop every keys
Object.keys(data).forEach((key) => {
// Append the text into the content
editor.write(`export const ${key}: "${data[key]}";\n`)
});
// Save everything and create file
editor.end()
选项 2:前端
<html>
<script>
const data = {
APP_NAME: "Test App",
APP_TITLE: "Hello World"
};
let content = '';
Object.keys(data).forEach((key) => {
// Append the text into the content
content += `export const ${key}: "${data[key]}";\n`;
});
let a = document.createElement('a');
a.href = "data:application/octet-stream,"+encodeURIComponent(content);
a.download = 'config.ts';
a.click();
</script>
</html>
推荐阅读
- python - 此代码应反转列表,但仅交换第一个和最后一个元素
- amazon-web-services - 位于运行脚本的 EC2 实例上的 S3 中的 EMR 日志在哪里?
- c++ - 在 CppUnit 中测试中止断言失败
- vba - VBA/规则更改传入电子邮件的主题行然后移动到文件夹
- angular - Angular DataTable(grid) 未与给定的 Json 数据绑定
- python - PANDAS 用逗号分隔符拆分列,列拆分数未知
- c# - 使用 post 调用 Web 服务器得到内部服务器错误
- ios - 致命异常:NSInternalInconsistencyException 如何找到违规代码?
- javascript - 如何正确地将 C# 对象列表解析为 Javascript。仅显示“System.Collections.Generic.List`1”之类的类型
- xml - 使用 XSD 确保 XML 验证中的字符串不为空