Download the JSON object as a file from the browser

I have the following code allowing users to load data rows into a csv file.

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

It works well that if the client runs the code, it generates a blank page and starts loading the data into the csv file.

So, I tried to do this using a JSON object like

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

But I only see the page with the JSON data displayed on it, and not the load.

I went through several studies and this one claims to work, but I don't see any difference with my code.

Am I missing something in my code?

Thanks for reading my question :)

+96
json javascript
Nov 01 '13 at 5:42
source share
10 answers

Here 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 save, and "scene.json" is just an example of a name for the resulting file.

This approach has the following advantages over others offered:

  • No HTML element need to click
  • The result will be named the way you want.
  • JQuery is not required

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

JS solution (HTML not 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(); } 
+138
Jun 12 '15 at 10:23
source share

Answer found.

 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 great for me.

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

+32
Dec 03 '13 at 6:02
source share

This will be a clean version of JS (adapted from cowboys):

 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

+22
Jun 09 '15 at 9:09
source share

The following worked for me:

 /* function to save JSON to file from browser * adapted from http://bgrins.imtqy.com/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 call him that

 saveJSON(myJsonObject, "saved_data.json"); 
+9
Jan 09 '17 at 17:23
source share

You can try using:

There is 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', name: fileName }); // Save the file saveAs(fileToSave, fileName); 

If you want to print JSON, then for this answer you can use:

 JSON.stringify(data,undefined,2) 
+7
Aug 09 '17 at 15:28
source share

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

+4
Aug 23 '14 at 0:15
source share

Recently I had to create a button that would load a json file with all the large form values. I needed this to work with IE / Edge / Chrome. Here 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 problem with the file name and extension in Edge, but at the time of writing this was an error in Edge that needs to be fixed.

Hope this helps someone

+3
Apr 13 '17 at 9:19 on
source share

A simple, clean solution for those who focus only on 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'); 
+3
Jun 09 '18 at 9:00
source share

Try setting a different MIME type: exportData = 'data:application/octet-stream;charset=utf-8,';

But there may be problems with the file name in the save dialog.

+1
Nov 01 '13 at 6:36
source share

React : Add this where you want in your rendering method.

• The facility is able to :

 <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 the requisite :

 <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, change the style to suit your needs.

+1
Oct 02 '18 at
source share



All Articles