oz2311 oz2311 - 7 months ago 20
Javascript Question

javascript JSON array to csv

Hey Guys i wanted to create a link which creates a csv of my JSON array.

My Code creates a CSV File every time when i reload my page
i can't see a link, where i can click. I'm really beginner of JS

Could Someone help me?

var csvContent = "data:text/csv;charset=utf-8,";

// Iterating through all the objects
data.forEach(function (infoArray, index) {

// Fetching all keys of a single object
var _keys = Object.keys(infoArray);
var dataString = [];

[].forEach.call(_keys, function(inst, i){
dataString.push(infoArray[inst]);
});

dataString = dataString.join(";");
csvContent += index < data.length ? dataString + "\n" : dataString;
});

var encodedUri = encodeURI(csvContent);window.open(encodedUri);
var encodedUri = encodeURI(csvContent);

var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
link.click();

Answer

I used it like this It works

<input id="csv" type="button" value="CSV">

    //--------------------------- CSV EXPORT --------------------------------

    var csvContent = "data:text/csv;charset=utf-8,";
    $("#csv").click(function(){
    // Iterating through all the objects
     data.forEach(function (infoArray, index) {

     // Fetching all keys of a single object
     var _keys = Object.keys(infoArray);
     var dataString = [];

    [].forEach.call(_keys, function(inst, i){
        dataString.push(infoArray[inst]);
     });

      dataString = dataString.join(";");
      csvContent += index < data.length ? dataString + "\n" : dataString;
    });


    var encodedUri = encodeURI(csvContent);
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "my_data.csv");
    link.click(); 

    });