Skip to main content
Commonmark migration
Source Link

CSV output

##CSV output alt text

##CSV output alt text

CSV output

alt text

added 3706 characters in body
Source Link
Sky Sanders
  • 12.1k
  • 3
  • 32
  • 60

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);
};

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);
};
Source Link
Sky Sanders
  • 12.1k
  • 3
  • 32
  • 60

##CSV output alt text

Any grid on StackUsers provides an Export CSV to Clipboard button that will copy the data from the current grid view. This includes all user fields, not limited to those shown in the grid.

The output is standard CSV and can be opened or consumed by any tabular data editor.

Anonymous StackUsers can page 50 rows, while registered users are provided larger datasets.

If you have registered and would like a record count increase to satisfy a particular usage requirement, just email me @ [email protected].