Sam Thadhani
Sam Thadhani

Reputation: 587

club json values together and create a csv

I have a json data that i would like to club and create a csv file thereafter. The json data looks like below. The data will not be the same always (like in first json object there are only two fields while in second and third there are 3 fields but some of these are different, actually, the data is form input and can be dynamic based on the input received on non-mandatory elements). The thing i am sure of is that only one JSON array will contain all the json

[{"firstName":"Kukreja","lastName":"Ramesh"},{"firstName":"Ram","lastName":"Laxman","dob":"jan-1990"},{"firstName":"Sam","resourceType":"/dmp/formdata","lastName":"Paul"}] 

I have to create a spreadsheet with this data. So the column heading should say firstName and all the json object values like kureja/Ram/Sam should appear in separate rows other data should be formatted accordingly in columns and rows.

Currently, i am using this function to create a csv

function ConvertToCSV(objArray) {

    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';

    for (var i = 0; i < array.length; i++) {
        var line = '';
        for (var index in array[i]) {
            if (line != '') line += ','
            console.log(array[i][index]);
            line += array[i][index];
        }

        str += line + '\r\n';
    }

    return str;
}

Upvotes: 0

Views: 306

Answers (1)

Luan Castro
Luan Castro

Reputation: 1184

you can use the function below...

FIXED EXAMPLE!.... please see again

see the example! -> http://jsfiddle.net/Castrolol/9m9W5/ in the example have a download metho too...

function json2csv(objArray, headers, showHeaders) {

    if( typeof headers == "boolean" ){
         showHeaders = headers;
        headers = null;
    }

    var itens = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

    //separate fields 
    var fields = {};

    if( !headers ){
        for(var i = 0; i < itens.length; i++){         
            for(var prop in itens[i]){             
                if( !fields[prop] ){                 
                    fields[prop] = [];                    
                }                
            }            
        }
    }else{
        headers.forEach(function(header){ fields[header] = []; });
    }


    //getting data

    for(var i = 0; i < itens.length; i++){        
        for(var prop in fields){            
            if( typeof itens[i][prop] != "undefined" ){
                fields[prop].push( itens[i][prop] );
            }else{
                fields[prop].push( "" );
            }            
        }        
    }

    //make the csv

    var csvLines = [];

    if( showHeaders ){

        var lineFields = [];

        for(var prop in fields){            
            lineFields.push(  prop );                        
        }

        var line = lineFields.join(", ");
        csvLines.push(line);        

    }

    for(var i = 0; i < itens.length; i++){

        var lineFields = [];

        for(var prop in fields){            
            lineFields.push(  fields[prop][i] );                        
        }

        var line = lineFields.join(", ");
        csvLines.push(line);        
    }

    var csvStr = "sep=,\n" + csvLines.join("\n");    

    return csvStr;
}

Upvotes: 1

Related Questions