174

Say I have a javascript object that looks like this :

  var data = {
      name: "cliff",
      age: "34"
    }

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.

4 Answers 4

323

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');
Sign up to request clarification or add additional context in comments.

12 Comments

it's possible, you just have to use input tag with type=file, like presented here: stackoverflow.com/questions/13709482/…
I get [object Object] when I do this
@JackNicholson I also just got [object Object].. I had to call JSON.stringify() first, and pass that value, rather than the object itself.
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: developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL.
@Enrique In node.js you can of course. In webapi user chooses destination directory, so no, you can't.
|
46

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>

4 Comments

Thanks a lot. Fantastic and simple solution using pure javascript .
It's just simply awesome!! :D
Thanks for the indentation tip for better json format JSON.stringify(originalData, null, 2). Also naming the file "data.json" should be more appropriate if it is a json file.
I second @Patronaut comment. Plus change type: "text/plain" to: type: "application/json"
11

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

1 Comment

"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.
8

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

2 Comments

I like this answer because it even works in console. thanks
...where is the file saved on a iPhone device???

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.