Q:

Javascript / convert json to csv

How to convert  an array of json object to csv ?
ex
[{ name: "Item 1", color: "Green", size: "X-Large" },
 { name: "Item 2", color: "Green", size: "X-Large" },
 { name: "Item 3", color: "Green", size: "X-Large" }];

give
name;color;size
Item 1;Green;X-Large
Item 2;Green;X-Large
Item 3;Green;X-Large

A:

Example in JSFiddle : http://jsfiddle.net/FLR4v/
Dependencies : 

Underscorejs http://underscorejs.org/underscore-min.js
Momentjs http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.0.0/moment.min.js

The function
 /**
 * Return a CSV string from an array of json object
 *
 * @method JSONtoCSV
 * @param {Object} jsonArray an array of json object
 * @param {String} [delimiter=;] delimiter
 * @param {String} [dateFormat=ISO] dateFormat if a date is detected
 * @return {String} Returns the CSV string
**/
function JSONtoCSV(jsonArray, delimiter, dateFormat){
    dateFormat = dateFormat || 'YYYY-MM-DDTHH:mm:ss Z'; // ISO
    delimiter = delimiter || ';' ;

    var body = '';
    // En tete
    var keys = _.map(jsonArray[0], function(num, key){ return key; });
    body += keys.join(delimiter) + '\r\n';
    // Data
    for(var i=0; i<jsonArray.length; i++){
        var item = jsonArray[i];
        for(var j=0; j<keys.length; j++){
            var obj = item[keys[j]] ;
            if (_.isDate(obj)) {                
                body += moment(obj).format(dateFormat) ;
            } else {
                body += obj ;
            }

            if (j < keys.length-1) { 
                body += delimiter; 
            }
        }
        body += '\r\n';
    }

    return body;
}

