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

tha*_*Guy 55 javascript json

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

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

var jsonData = JSON.stringify(data);
Run Code Online (Sandbox Code Playgroud)

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

Raf*_*ski 131

Node.js的:

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

浏览器(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');
Run Code Online (Sandbox Code Playgroud)

  • @JackNicholson我也刚刚得到`[object Object]`我必须首先调用`JSON.stringify()`,然后传递*that*值,而不是对象本身. (29认同)
  • 当我这样做时,我得到`[object Object]` (9认同)
  • 在`a.click()`之后,我们应该调用`revokeObjectURL`,以便让浏览器知道不再保留对文件的引用:`URL.revokeObjectURL(a.href)。`更多信息:https:// /developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL。 (6认同)
  • 它是可能的,你只需要使用type = file的输入标签,如下所示:http://stackoverflow.com/questions/13709482/how-to-read-text-file-in-javascript (2认同)
  • @Enrique 在node.js 中你当然可以。在 webapi 中,用户选择目标目录,所以不,你不能。 (2认同)

dab*_*eng 13

这是我将本地数据保存到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);
}
Run Code Online (Sandbox Code Playgroud)
<button onclick="export2txt()">Export data to local txt file</button>
Run Code Online (Sandbox Code Playgroud)

  • 感谢您提供更好的 json 格式“JSON.stringify(originalData, null, 2)”的缩进提示。如果文件是 json 文件,则将文件命名为“data.json”应该更合适。 (3认同)
  • 我同意@Patronaut 的评论。另外将 `type: "text/plain"` 更改为: `type: "application/json"` (3认同)

小智 6

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


Jcc*_*ria 6

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

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();
Run Code Online (Sandbox Code Playgroud)