Implementation
For those interested in converting a homogeneous array of JavaScript objects to CSV, here is the code that I use on StackUsers.
It is freely offered without restriction.
jsonToCSV
function jsonToCSV(sourceRows, omitHeader, fieldsToIgnore)
{
/// <summary>
/// Converts an array of JSON objects to CSV.
///</summary>
/// <param name="sourceRows" type="Object[]">
/// An array of objects containing a single level of scalar fields.
/// e.g. [{ foo: "bar", fu: true }, { foo: "baarbar", fu: false }]
///
/// The first element in the array will define the header row.
/// </param>
/// <param name="omitHeader" type="Boolean" optional="true">if true, header row is not emitted</param>
/// <param name="fieldsToIgnore" type="Map" optional="true">a map of fields to ignore e.g. { field1:1,field4:1 }</param>
/// <returns type="String"></returns>
/// <author name="sky sanders" contact="http://skysanders.net/subtext" date="2010-09-19"/>
function quote(value)
{
return '"' + value.replace(/"/g, '""').replace(/\r/g, "\\r").replace(/\n/g, "\\b") + '"';
};
function pad(n)
{
return n < 10 ? '0' + n : n;
};
var header = "";
var rows = "";
var headerComplete = false;
for (var i = 0; i < sourceRows.length; i++)
{
var firstElement = true;
var row = "";
for (var key in sourceRows[i])
{
if (sourceRows[i].hasOwnProperty(key))
{
if (fieldsToIgnore && (key in fieldsToIgnore))
{
continue;
}
if (!headerComplete)
{
if (!firstElement)
{
header = header.concat(", ");
};
header = header.concat(key);
};
if (!firstElement)
{
row = row.concat(", ");
};
var value = sourceRows[i][key];
if (typeof value != 'undefined' && value !== null)
{
if (value instanceof Date)
{
var dateResult = value.getUTCFullYear() + '-'
+ pad(value.getUTCMonth() + 1) + '-'
+ pad(value.getUTCDate()) + 'T'
+ pad(value.getUTCHours()) + ':'
+ pad(value.getUTCMinutes()) + ':'
+ pad(value.getUTCSeconds()) + 'Z';
row = row.concat(dateResult);
}
else if ((value instanceof Boolean) || !isNaN(value))
{
row = row.concat(value.valueOf());
}
else
{
row = row.concat(quote(value.valueOf()));
}
}
firstElement = false;
}
}
rows = rows.concat(row).concat("\r\n");
headerComplete = true;
}
return omitHeader ? rows : header.concat("\r\n").concat(rows);
};