【问题标题】:How do I save JSON to local text file如何将 JSON 保存到本地文本文件
【发布时间】:2016-03-13 09:30:46
【问题描述】:

假设我有一个看起来像这样的 javascript 对象:

  var data = {
      name: "cliff",
      age: "34",
      name: "ted",
      age: "42",
      name: "bob",
      age: "12"
    }

var jsonData = JSON.stringify(data);

我将其字符串化以转换为 JSON。如何将此 JSON 保存到本地文本文件中,以便可以在记事本等中打开它。

【问题讨论】:

    标签: javascript json


    【解决方案1】:

    Node.js:

    var fs = require('fs');
    fs.writeFile("test.txt", jsonData, function(err) {
        if (err) {
            console.log(err);
        }
    });
    

    浏览器(webapi):

    function download(content, fileName, contentType) {
        var a = document.createElement("a");
        var file = new Blob([content], {type: contentType});
        a.href = URL.createObjectURL(file);
        a.download = fileName;
        a.click();
    }
    download(jsonData, 'json.txt', 'text/plain');
    

    【讨论】:

    • 有可能,您只需使用 type=file 的输入标签,如下所示:stackoverflow.com/questions/13709482/…
    • 当我这样做时我得到[object Object]
    • @JackNicholson 我也刚得到[object Object]。我必须先调用JSON.stringify(),然后传递那个值,而不是对象本身。
    • a.click()之后,我们应该调用revokeObjectURL以便让浏览器知道不再保留对文件的引用:URL.revokeObjectURL(a.href).更多信息:developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL
    • @Enrique 在 node.js 中你当然可以。在 webapi 用户选择目标目录,所以不,你不能。
    【解决方案2】:

    将本地数据保存到txt文件是我的解决方案。

    function export2txt() {
      const originalData = {
        members: [{
            name: "cliff",
            age: "34"
          },
          {
            name: "ted",
            age: "42"
          },
          {
            name: "bob",
            age: "12"
          }
        ]
      };
    
      const a = document.createElement("a");
      a.href = URL.createObjectURL(new Blob([JSON.stringify(originalData, null, 2)], {
        type: "text/plain"
      }));
      a.setAttribute("download", "data.txt");
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
    <button onclick="export2txt()">Export data to local txt file</button>

    【讨论】:

    • 非常感谢。使用纯 javascript 的奇妙而简单的解决方案。
    • 简直太棒了!! :D
    【解决方案3】:

    这里是纯js的解决方案。您可以使用 html5 saveAs 来完成。例如,这个库可能会有所帮助:https://github.com/eligrey/FileSaver.js
    看演示:http://eligrey.com/demos/FileSaver.js/
    附言没有关于 json 保存的信息,但是您可以将文件类型更改为 "application/json" 并将格式更改为 .json

    【讨论】:

    • "application/json" 和 .json 适用于 html 文件系统。还使用它来防止任何 json 解析错误,例如“Unexpected token ? in JSON”。谢谢。
    【解决方案4】:

    拿了dabeng's solution,我已经把它转录成一个类方法了。

    class JavascriptDataDownloader {
    
        constructor(data={}) {
            this.data = data;
        }
    
        download (type_of = "text/plain", filename= "data.txt") {
            let body = document.body;
            const a = document.createElement("a");
            a.href = URL.createObjectURL(new Blob([JSON.stringify(this.data, null, 2)], {
                type: type_of
            }));
            a.setAttribute("download", filename);
            body.appendChild(a);
            a.click();
            body.removeChild(a);
        }
    } 
    
    new JavascriptDataDownloader({"greetings": "Hello World"}).download();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      相关资源
      最近更新 更多