0

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);
Cœur
  • 37,241
  • 25
  • 195
  • 267
Peter Pik
  • 11,023
  • 19
  • 84
  • 142
  • Check this out: http://stackoverflow.com/questions/4130849/convert-json-format-to-csv-format-for-ms-excel/4130939#4130939 – Proqb Aug 19 '15 at 11:53

1 Answers1

3

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

vijay shiyani
  • 766
  • 7
  • 19