John Davidson

javascript - Download JSON object as a file from browser

0 comments
Message:


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



My Answer:
Yes, you are missing one key step in your code to download the JSON object as a file. Instead of opening a new window with the encoded URI, you should create a link element and trigger a click event on it to download the file.

Here is the updated code:

javascript
var jsonObject = { key: 'value' };
var exportData = 'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(jsonObject));
var link = document.createElement('a');
link.setAttribute('href', exportData);
link.setAttribute('download', 'data.json');
document.body.appendChild(link);
link.click();


In this code snippet, we create a link element with the encoded URI as the href attribute and set the download attribute to specify the filename for the downloaded file. Then, we append the link to the document body and trigger a click event on it to initiate the download.

This should work to download the JSON object as a file from the browser.

Rate this post

3 of 5 based on 8859 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us