简体   繁体   English

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

[英]How do I save JSON to local text file

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.我将其字符串化以转换为 JSON。 How do I save this JSON to a local text file so I can open it, say, in Notepad etc.如何将此 JSON 保存到本地文本文件中,以便可以在记事本等中打开它。

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

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>

Here is a solution on pure js.这是纯js的解决方案。 You can do it with html5 saveAs.您可以使用 html5 saveAs 来完成。 For example this lib could be helpful: https://github.com/eligrey/FileSaver.js例如,这个库可能会有所帮助: https ://github.com/eligrey/FileSaver.js
Look at the demo: http://eligrey.com/demos/FileSaver.js/看演示: http ://eligrey.com/demos/FileSaver.js/
PS There is no information about json save, but you can do it changing file type to "application/json" and format to .json PS没有关于json保存的信息,但是您可以将文件类型更改为"application/json"并将格式更改为.json

import { saveAs } from 'file-saver'

let data = { a: 'aaa' , b: 'bbb' }

let blob = new Blob([JSON.stringify(data)], { type: 'application/json' })
    
saveAs(blob, 'export.json')

Took dabeng's solution and I have transcribed it as a class method.拿了大崩的解决方案,我已经把它转录成一个类方法了。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM