Ad Code

Ticker

6/recent/ticker-posts

create csv file from json data in javascript

Download CSV from JSON data using JavaScript

create csv file from json data in javascript


There is a java-script small function which is created a CSV file.

<input type="hidden" id="jsndata" value='[{Name: "Dharmendra", Age: 45}, {Name: "Frank", Age: 19}, {Name: "Henry", Age: 43}]'/>
<input type="button" id="dnbtn" value="Download"/>

function JSONToCSVCreater(JSONData, ReportTitle, ShowLabel) {
    var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
    
    var CSV = '';
    if (ShowLabel) {
        var row = "";
        
        for (var index in arrData[0]) {
            row += index + ',';
        }

        row = row.slice(0, -1);
        CSV += row + '\r\n';
    }
    for (var i = 0; i < arrData.length; i++) {
        var row = "";
        for (var index in arrData[i]) {
            row += '"' + arrData[i][index] + '",';
        }

        row.slice(0, row.length - 1);
        CSV += row + '\r\n';
    }

    if (CSV == '') {        
        alert("Invalid data");
        return;
    }
    var fileName = "PriyaDigiTech_";
    fileName += ReportTitle.replace(/ /g,"_");   
    
    var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);
    
    var link = document.createElement("a");    
    link.href = uri;
    
    link.style = "visibility:hidden";
    link.download = fileName + ".csv";
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}
// this function use to create on click event
    $('#dnbtn').click(function(){
        var data = $('#jsndata').val();
        if(data == '')
           return;
        JSONToCSVCreater(data, "CSVFILENAME", true);
    });

The above code is used to create a CSV file from any type but the main requirement is the javascript function pass parameter data as JSON data.

If you have an array of data you want to create a CSV file from that array then you can parse it into JSON format, the main things are the array associated array and not the multilevel array.

If an array has an associated and multilevel array then firstly you should convert it into a single level like this...

Example,

    array(
             array('name'=>'Priya Digital Technology','visitor'=>'1000','time-period'=>'10'),
             array('name'=>'Priya Digital Technology','visitor'=>'1000','time-period'=>'10')
            );

Then convert to JSON format.

  in php convert,           json_encode(array());

Then convert it to JSON like this format,

    [{'name':'Priya Digital Technology','visitor':'1000','time-period':'10'},{'name':'Priya Digital Technology','visitor':'1000','time-period':'10'}]

                 

Post a Comment

0 Comments

Ad Code