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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34156282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:58:14  来源:igfitidea点击:

How do I save JSON to local text file

javascriptjson

提问by thatOneGuy

Say I have a javascript object that looks like this :

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

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

var jsonData = JSON.stringify(data);

I stringify it to convert to JSON. How do I save this JSON to a local text file so I can open it, say, in Notepad etc.

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

回答by Rafa? ?u?yński

Node.js:

节点.js:

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

Browser (webapi):

浏览器(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');

回答by aslantorret

Here is a solution on pure js. You can do it with html5 saveAs. For example this lib could be helpful: https://github.com/eligrey/FileSaver.js
Look at the demo: http://eligrey.com/demos/FileSaver.js/
P.S. There is no information about json save, but you can do it changing file type to "application/json"and format to .json

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

回答by dabeng

It's my solution to save local data to txt file.

这是我将本地数据保存到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>