242

I have the following code to let users download data strings in csv file.

exportData = 'data:text/csv;charset=utf-8,';
exportData += 'some csv strings';
encodedUri = encodeURI(exportData);
newWindow = window.open(encodedUri);

It works just fine that if client runs the code it generates blank page and starts downloading the data in csv file.

So I tried to do this with JSON object like

exportData = 'data:text/json;charset=utf-8,';
exportData += escape(JSON.stringify(jsonObject));
encodedUri = encodeURI(exportData);
newWindow = window.open(encodedUri);

But I see only a page with the JSON data displayed on it, not downloading it.

I went through some research and this one claims to work but I don't see any difference to my code.

Am I missing something in my code?

Thanks for reading my question:)

15 Answers 15

411

This is how I solved it for my application:

HTML: <a id="downloadAnchorElem" style="display:none"></a>

JS (pure JS, not jQuery here):

var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(storageObj));
var dlAnchorElem = document.getElementById('downloadAnchorElem');
dlAnchorElem.setAttribute("href",     dataStr     );
dlAnchorElem.setAttribute("download", "scene.json");
dlAnchorElem.click();

In this case, storageObj is the js object you want to store, and "scene.json" is just an example name for the resulting file.

This approach has the following advantages over other proposed ones:

  • No HTML element needs to be clicked
  • Result will be named as you want it
  • no jQuery needed

I needed this behavior without explicit clicking since I want to trigger the download automatically at some point from js.

JS solution (no HTML required):

  function downloadObjectAsJson(exportObj, exportName){
    var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
    var downloadAnchorNode = document.createElement('a');
    downloadAnchorNode.setAttribute("href",     dataStr);
    downloadAnchorNode.setAttribute("download", exportName + ".json");
    document.body.appendChild(downloadAnchorNode); // required for firefox
    downloadAnchorNode.click();
    downloadAnchorNode.remove();
  }
16
  • 4
    This is the only solution that will work for more than =~ 2000 characters of data. Because you prepended data:
    – rjurney
    Feb 1, 2016 at 21:23
  • 1
    Can somebody point me to a spec or MDN page that explains in more detail how this whole prepended data-type thing works ie. "data:text/json;charset=utf-8"? I am using this, but it feels like magic, would be great to read up on the details but I don't even know how to google for it. Jul 25, 2016 at 20:02
  • 1
    This doesn't work in IE though when you have to download a big file with more than 2000 characters.
    – user388969
    Feb 16, 2017 at 15:38
  • 12
    This will not work without limits, though. You can only download about 1MB of data. For example, var storageObj = []; for (var i=0; i<1000000; ++i) storageObj.push('aaa'); gives "download Failed - Network error" in Chrome 61
    – oseiskar
    Nov 1, 2017 at 12:19
  • 3
    @YASHDAVE use JSON.stringify(exportObj, null, 2) instead May 8, 2018 at 8:43
45

Found an answer.

var obj = {a: 123, b: "4 5 6"};
var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));

$('<a href="data:' + data + '" download="data.json">download JSON</a>').appendTo('#container');

seems to work fine for me.

** All credit goes to @cowboy-ben-alman, who is the author of the code above **

3
  • @Cybear can you explain the third line to me? May 4, 2015 at 11:12
  • You will want to prepend data: to your url, otherwise the user is likely to hit a 2000 character limit in many browsers.
    – rjurney
    Feb 1, 2016 at 21:24
  • Hey , I know it is an old answer but, know this solution doesn't work on IE (all of them) IE does not familiar with download attribute reference - link Aug 10, 2017 at 13:35
44

You could try using:

  • the native JavaScript API's Blob constructor and
  • the FileSaver.js saveAs() method

No need to deal with any HTML elements at all.

var data = {
    key: 'value'
};
var fileName = 'myData.json';

// Create a blob of the data
var fileToSave = new Blob([JSON.stringify(data)], {
    type: 'application/json'
});

// Save the file
saveAs(fileToSave, fileName);

If you wanted to pretty print the JSON, per this answer, you could use:

JSON.stringify(data,undefined,2)
5
  • 3
    saveAs() is from FileSaver.js - github.com/eligrey/FileSaver.js
    – Gautham
    Sep 5, 2017 at 8:29
  • 5
    "No need to deal with any HTML elements at all" ... and reading the source code of filesaver.js ... it does exactly that lol
    – War
    Sep 24, 2017 at 15:55
  • 2
    Yeah. I meant to say, no need to deal with the HTML elements directly.
    – Gautham
    Sep 25, 2017 at 16:43
  • 3
    This is the best answer since it does not have a 1MB size limit and uses a library instead of custom hacks
    – oseiskar
    Nov 1, 2017 at 12:41
  • FileSaver.js is very heavy for doing a simple file download. Check my answer down below; CTRL+F and search for "ES6+".
    – MSOACC
    Jan 28, 2021 at 14:31
34

ES6+ version for 2021; no 1MB limit either:

This is adapted from @maia's version, updated for modern Javascript with the deprecated initMouseEvent replaced by new MouseEvent() and the code generally improved:

const saveTemplateAsFile = (filename, dataObjToWrite) => {
    const blob = new Blob([JSON.stringify(dataObjToWrite)], { type: "text/json" });
    const link = document.createElement("a");

    link.download = filename;
    link.href = window.URL.createObjectURL(blob);
    link.dataset.downloadurl = ["text/json", link.download, link.href].join(":");

    const evt = new MouseEvent("click", {
        view: window,
        bubbles: true,
        cancelable: true,
    });

    link.dispatchEvent(evt);
    link.remove()
};

If you want to pass an object in:

saveTemplateAsFile("filename.json", myDataObj);
3
  • 2
    I believe you should clean link after you're done with it, by calling link.remove() Feb 2, 2021 at 11:35
  • 2
    I'm offering a download in an offline html/js file and this is simpler than FileSaver.js for me. Thank you!
    – Dave C
    Sep 15, 2021 at 14:16
  • FYI the official JSON media type is application/json as per its RFC. Aug 27 at 13:01
30

Simple, clean solution for those who only target modern browsers:

function downloadTextFile(text, name) {
  const a = document.createElement('a');
  const type = name.split(".").pop();
  a.href = URL.createObjectURL( new Blob([text], { type:`text/${type === "txt" ? "plain" : type}` }) );
  a.download = name;
  a.click();
}

downloadTextFile(JSON.stringify(myObj), 'myObj.json');
0
29

This would be a pure JS version (adapted from cowboy's):

var obj = {a: 123, b: "4 5 6"};
var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));

var a = document.createElement('a');
a.href = 'data:' + data;
a.download = 'data.json';
a.innerHTML = 'download JSON';

var container = document.getElementById('container');
container.appendChild(a);

http://jsfiddle.net/sz76c083/1

4
  • 3
    Thanks for the response even after it's been 2yrs since I asked this question! I prefer pure JS over jQuery syntax.
    – Eugene Yu
    Dec 3, 2015 at 5:39
  • You will want to prepend data: to your url, otherwise the user is likely to hit a 2000 character limit in many browsers.
    – rjurney
    Feb 1, 2016 at 21:23
  • how can i make this download start on the page load. whenever a user browse the page url he gets prompt for download
    – user388969
    Feb 16, 2017 at 0:08
  • 1
    Today's test in Edge: data.json could not be downloaded. Nov 2, 2019 at 15:37
24

The following worked for me:

/* function to save JSON to file from browser
* adapted from http://bgrins.github.io/devtools-snippets/#console-save
* @param {Object} data -- json object to save
* @param {String} file -- file name to save to 
*/
function saveJSON(data, filename){

    if(!data) {
        console.error('No data')
        return;
    }

    if(!filename) filename = 'console.json'

    if(typeof data === "object"){
        data = JSON.stringify(data, undefined, 4)
    }

    var blob = new Blob([data], {type: 'text/json'}),
        e    = document.createEvent('MouseEvents'),
        a    = document.createElement('a')

    a.download = filename
    a.href = window.URL.createObjectURL(blob)
    a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':')
    e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
    a.dispatchEvent(e)
}

and then to call it like so

saveJSON(myJsonObject, "saved_data.json");
2
  • 5
    While this is a great answer, initMouseEvent() is a deprecated Web Standard and should not be used anymore. Instead, use the new MouseEvent() interface. It's just a minor refactor though.
    – morkro
    May 28, 2017 at 8:16
  • @morkro is correct; I have posted an answer below that builds and improves on @maia's answer with initMouseEvent removed (and the code generally cleaned up)
    – MSOACC
    Jan 28, 2021 at 14:28
18

I recently had to create a button that would download a json file of all values of a large form. I needed this to work with IE/Edge/Chrome. This is what I did:

function download(text, name, type)
    {
        var file = new Blob([text], {type: type});
        var isIE = /*@cc_on!@*/false || !!document.documentMode;
        if (isIE)
        {
            window.navigator.msSaveOrOpenBlob(file, name);
        }
        else
        {
            var a = document.createElement('a');
            a.href = URL.createObjectURL(file);
            a.download = name;
            a.click();
        }
     }

download(jsonData, 'Form_Data_.json','application/json');

There was one issue with filename and extension in edge but at the time of writing this seemed to be a bug with Edge that is due to be fixed.

Hope this helps someone

2
  • This worked on Chrome, but doesn't seem to work on Firefox... please help! codepen.io/anon/pen/ePYPJb Sep 28, 2018 at 13:32
  • 1
    Nice function, add document.body.appendChild(a); a.style.display = 'none'; to make it work in Firefox. Jan 16, 2019 at 9:25
7
    downloadJsonFile(data, filename: string){
        // Creating a blob object from non-blob data using the Blob constructor
        const blob = new Blob([JSON.stringify(data)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        // Create a new anchor element
        const a = document.createElement('a');
        a.href = url;
        a.download = filename || 'download';
        a.click();
        a.remove();
      }

You can easily auto download file with using Blob and transfer it in first param downloadJsonFile. filename is name of file you wanna set.

6

If you prefer console snippet, raser, than filename, you can do this:

window.open(URL.createObjectURL(
    new Blob([JSON.stringify(JSON)], {
      type: 'application/binary'}
    )
))
5

The download property of links is new and not is supported in Internet Explorer (see the compatibility table here). For a cross-browser solution to this problem I would take a look at FileSaver.js

5

React: add this where you want in your render method.

• Object in state:

<a
  className="pull-right btn btn-primary"
  style={{ margin: 10 }}
  href={`data:text/json;charset=utf-8,${encodeURIComponent(
  JSON.stringify(this.state.objectToDownload)
  )}`}
  download="data.json"
>
  DOWNLOAD DATA AS JSON
</a>

• Object in props:

<a
  className="pull-right btn btn-primary"
  style={{ margin: 10 }}
  href={`data:text/json;charset=utf-8,${encodeURIComponent(
  JSON.stringify(this.props.objectToDownload)
  )}`}
  download="data.json"
>
  DOWNLOAD DATA AS JSON
</a>

className and style are optional, modify the style according to your needs.

2

Try to set another MIME-type: exportData = 'data:application/octet-stream;charset=utf-8,';

But there are can be problems with file name in save dialog.

2
  • Sorry for coming back to you late. I tried your answer and it does download file but contains wrong data in it.. :(
    – Eugene Yu
    Nov 5, 2013 at 22:14
  • 2
    this worked for me... data = "data:application/octet-stream;charset=utf-8," + encodeURIComponent(JSON.stringify(data)); window.open(data); it simply downloads the file as "download" but the data i stringified and then uri-encoded is as it should be. Oct 7, 2014 at 15:47
2

Here's a simple version adapted from @Mohammed/@Maia working in modern browsers:

function saveAsFile(filename, data) {

    const blob = new Blob([JSON.stringify(data)]);
    const link = document.createElement("a");
    link.download = filename;
    link.href = window.URL.createObjectURL(blob);
    link.click()

};

Which can be used as

saveAsFile('posts.json', posts)
0

const exportToJson = (data: {}) =>{

const link = document.createElement("a");
link.href = data:text/json;charset=utf8,${encodeURIComponent(JSON.stringify(data))}; link.download = 'example.json'; link.click(); }

Make sure to clean up the the created link after if you don't want a random element that does nothing.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.