首页 > 解决方案 > 如何使用我自己的格式将 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";

标签: javascriptjsonangularfile

解决方案


对于这种情况,您可以使用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>

推荐阅读