【问题标题】:How can I convert a JSON object into javascript file with my own format如何使用我自己的格式将 JSON 对象转换为 javascript 文件
【发布时间】:2021-12-23 17:40:35
【问题描述】:

我有一个这样的 json 对象

{
   APP_NAME: "Test App",
   APP_TITLE: "Hello World"
}

现在我想将其转换为 javascript 文件并下载该文件 文件格式应该是这样的

// config.ts

export const APP_NAME: "Test App";
export const APP_TITLE: "Hello World";

【问题讨论】:

  • 浏览器没有本地文件访问权限,因此如果您在浏览器中将其作为 JavaScript 运行,您将无法将文件放在特定位置。如果您只想让浏览器下载文件并将其放入系统的下载目录中,则可以使用此 SO 答案将字符串下载为文件:stackoverflow.com/questions/3665115/…

标签: javascript json angular file


【解决方案1】:

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

【讨论】:

  • @Adian Arif Zakaria,关于我们如何在 React.js 或 Angular js 中做同样的事情的任何想法,因为 fs 不能在客户端工作
  • @JagannathSwarnkar 我已经更新了我的代码
猜你喜欢
  • 1970-01-01
  • 2020-02-21
  • 2022-06-10
  • 1970-01-01
  • 2012-06-30
  • 1970-01-01
  • 2016-12-26
  • 2018-04-28
相关资源
最近更新 更多