如何将 JSON 保存到本地文本文件

IT技术 javascript json
2021-01-28 08:23:25

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

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

var jsonData = JSON.stringify(data);

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

4个回答

节点.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');
@Enrique 在 node.js 中,你当然可以。在 webapi 用户选择目标目录,所以不,你不能。
2021-03-20 08:23:25
有可能,你只需要使用 type=file 的输入标签,就像这里展示的一样:stackoverflow.com/questions/13709482/...
2021-03-23 08:23:25
我得到[object Object]我这样做的时候
2021-04-02 08:23:25
@JackNicholson 我也刚得到[object Object].. 我必须先调用JSON.stringify(),然后传递值,而不是对象本身。
2021-04-09 08:23:25
之后a.click(),我们应该调用revokeObjectURL以让浏览器知道不再保留对文件的引用:URL.revokeObjectURL(a.href).更多信息:developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL
2021-04-11 08:23:25

这是我将本地数据保存到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 的奇妙而简单的解决方案。
2021-03-16 08:23:25
简直太棒了!!:D
2021-03-28 08:23:25

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

"application/json" 和 .json 适用于 html 文件系统。还使用它来防止任何 json 解析错误,例如“意外的令牌?在 JSON”。谢谢。
2021-03-15 08:23:25

采取dabeng 的解决方案,我将其转录为类方法。

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();