Download JSON object as a file from browser

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

13 Answers
13

Leave a Comment