snippetjavascriptTip
Convert between CSV and JavaScript arrays, objects or JSON
Viewed 0 times
javascriptandbetweenobjectsarraysjsonconvertcsv
Problem
Comma-separated values (CSV) is a simple text format for storing tabular data. Each line in a CSV file represents a row, and each value in a row is separated by a delimiter, usually a comma. As CSV is used very often for exchanging data between different systems, it's important to know how to convert between JavaScript arrays or objects and CSV data.
> [!NOTE]
>
> As CSV format RFC 4180 is not standardized, there are many variations in how CSV data is formatted. This guide will cover the most common cases, but you may need to adjust the code to fit your specific use-case (see the table below for edge cases and how they are handled).
Serializing data to CSV is generally straightforward. Using
> [!NOTE]
>
> As CSV format RFC 4180 is not standardized, there are many variations in how CSV data is formatted. This guide will cover the most common cases, but you may need to adjust the code to fit your specific use-case (see the table below for edge cases and how they are handled).
Serializing data to CSV is generally straightforward. Using
Array.prototype.join() with a delimiter of your choice, you can easily create a single row from an array of values.Solution
const serializeRow = (row, delimiter = ',') => row.join(delimiter);
serializeRow(['a', 'b']);
// 'a,b'
serializeRow(['a', 'b'], ';');
// 'a;b'>
> As CSV format RFC 4180 is not standardized, there are many variations in how CSV data is formatted. This guide will cover the most common cases, but you may need to adjust the code to fit your specific use-case (see the table below for edge cases and how they are handled).
Serializing data to CSV is generally straightforward. Using
Array.prototype.join() with a delimiter of your choice, you can easily create a single row from an array of values.However, there are edge cases that need handling. These include empty values, values that contain the delimiter character, values that contain newlines, and values that contain double quotes. Here's a handy table of edge cases and how to handle them:
| Case | Sample value | CSV representation |
| --- | --- | --- |
Code Snippets
const serializeRow = (row, delimiter = ',') => row.join(delimiter);
serializeRow(['a', 'b']);
// 'a,b'
serializeRow(['a', 'b'], ';');
// 'a;b'const isEmptyValue = value =>
value === null || value === undefined || Number.isNaN(value);
const serializeValue = (value, delimiter = ',') => {
if (isEmptyValue(value)) return '';
value = `${value}`;
if (
value.includes(delimiter) ||
value.includes('\n') ||
value.includes('"')
)
return `"${value.replace(/"/g, '""').replace(/\n/g, '\\n')}"`;
return value;
};
const serializeRow = (row, delimiter = ',') =>
row.map(value => serializeValue(`value`, delimiter)).join(delimiter);
serializeRow(['a', 'b']);
// 'a,b'
serializeRow(['a', null]);
// 'a,'
serializeRow(['a,b', 'c']);
// '"a,b",c'
serializeRow(['a\nb', 'c']);
// '"a\\nb",c'
serializeRow(['a"b', 'c']);
// '"a""b",c'const arrayToCSV = (arr, delimiter = ',') =>
arr.map(row => serializeRow(row, delimiter)).join('\n');
arrayToCSV([['a', 'b'], ['c', 'd']]);
// 'a,b\nc,d'
arrayToCSV([['a,b', 'c'], ['d', 'e\n"f"']]) ;
// '"a,b",c\nd,"e\\n""f"""'Context
From 30-seconds-of-code: convert-csv-to-array-object-or-json
Revisions (0)
No revisions yet.