Reputation: 11193
I have created below code which takes a JSON object and convert it to comma separated through the ConvertToCSV function. My question is then how i can take the variable csvData and download it as a csv file?
This code is already in a function which is being executed on button click
var jsonObject = JSON.stringify(data);
var toCSV = ConvertToCSV(jsonObject);
var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(toCSV);
Upvotes: 0
Views: 588
Reputation: 766
use blob to store it locally and then download it. e.g
http://jsfiddle.net/koldev/cw7w5/
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
var data = { x: 42, s: "hello, world", d: new Date() },
fileName = "my-download.json";
saveData(data, fileName);
this http://jsfiddle.net/e5ggkkur/1/ will work in firefox
Upvotes: 3