152

Say I have a javascript object that looks like this :

  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.

thatOneGuy
  • 9,977
  • 7
  • 48
  • 90

4 Answers4

304

Node.js:

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

Browser (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');
Rafał Łużyński
  • 7,083
  • 5
  • 26
  • 38
  • Perfect. Thankyou. I know it's a different question completely, how difficult is it to get chrome to load JSON from local file ? Read a few places it's not possible due to Chrome's security... – thatOneGuy Dec 08 '15 at 13:00
  • 3
    it's possible, you just have to use input tag with type=file, like presented here: http://stackoverflow.com/questions/13709482/how-to-read-text-file-in-javascript – Rafał Łużyński Dec 08 '15 at 13:03
  • you have just saved me a lot of time. Very much appreciated. Thank you :)) – thatOneGuy Dec 08 '15 at 13:04
  • 16
    I get `[object Object]` when I do this – Jack Mar 22 '17 at 01:53
  • 52
    @JackNicholson I also just got `[object Object]`.. I had to call `JSON.stringify()` first, and pass *that* value, rather than the object itself. – ne1410s Jun 21 '17 at 14:42
  • I added JSON.stringify() inside the function, inside a if checking for contentType == 'application/json'. Tks for that code. Works like a charm. – Lovato Nov 15 '18 at 21:24
  • 1
    It worked for me, but what if i don't want to replace the file but instead append text to file? – Cesar Leonardo Ochoa Contreras Apr 19 '19 at 02:59
  • 8
    After `a.click()`, we should call `revokeObjectURL` in order to let the browser know not to keep the reference to the file any longer: `URL.revokeObjectURL(a.href).` More info: https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL. – andreivictor Jul 05 '19 at 12:50
  • is possible to save to a custom folder? if I use "myfolder/myfile.json" it is converted to myfolder_myfile.json – Enrique Aug 24 '19 at 19:08
  • 2
    @Enrique In node.js you can of course. In webapi user chooses destination directory, so no, you can't. – Rafał Łużyński Aug 27 '19 at 10:03
  • Is it possible to use this approach to save the file in "Save As" mode? (so I can get a confirmation dialog to possibly save in a different location than the default Downloads folder) Thanks! – Mark Betnel Nov 24 '19 at 22:39
  • I think question was not about Node.js explicitly. thanks – MindRoasterMir Oct 31 '21 at 15:44
38

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

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>
dabeng
  • 1,340
  • 17
  • 7
8

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

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')
Ivan Bacher
  • 5,855
  • 9
  • 36
  • 56
aslantorret
  • 273
  • 4
  • 10
  • "application/json" and .json works well with html file system. Also using this to prevent any json parse errors such as "Unexpected token ? in JSON". Thanks. – Ajay Singh Jan 12 '18 at 20:19
6

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();
traktor
  • 17,588
  • 4
  • 32
  • 53
Jcc.Sanabria
  • 629
  • 1
  • 12
  • 22