ParseCSV / FormatCSV (CSV data)
SyncJS provides two functions for working with CSV (Comma-Separated Values) data according to RFC 4180.
NOTE
These functions are available as of Syncplify Server! v7.1.1. If you are running an older version, upgrade to v7.1.1 or later to use them.
ParseCSV
ts
function ParseCSV(text: string, delimiter?: string): string[][];Parses a CSV string and returns a two-dimensional array of strings (an array of rows, where each row is an array of field values). Quoted fields, embedded commas, and embedded newlines are all handled correctly.
| Parameter | Type | Requirement | Explanation |
|---|---|---|---|
text | string | required | The CSV text to parse |
delimiter | string | optional | Single-character field delimiter. Defaults to , (comma). |
| Return value | Explanation |
|---|---|
string[][] | Two-dimensional array of field values |
null | The input could not be parsed as CSV |
Example
ts
var csv = 'Alice,30,Engineer\nBob,25,Designer\n';
var rows = ParseCSV(csv);
for (var i = 0; i < rows.length; i++) {
Log(rows[i][0] + ' is ' + rows[i][1] + ' years old.');
}
// Alice is 30 years old.
// Bob is 25 years old.Tab-separated example
ts
var tsv = 'col1\tcol2\tcol3\n1\t2\t3\n';
var rows = ParseCSV(tsv, '\t');FormatCSV
ts
function FormatCSV(rows: string[][], delimiter?: string): string;Serializes a two-dimensional array of strings to a CSV string. Fields are quoted automatically when they contain the delimiter, a double-quote, or a newline character, as required by RFC 4180.
| Parameter | Type | Requirement | Explanation |
|---|---|---|---|
rows | string[][] | required | Two-dimensional array of field values |
delimiter | string | optional | Single-character field delimiter. Defaults to , (comma). |
| Return value | Explanation |
|---|---|
| string | The CSV-formatted text |
Example
ts
var rows = [
['Name', 'Age', 'Role'],
['Alice', '30', 'Engineer'],
['Bob', '25', 'Designer']
];
var csv = FormatCSV(rows);
WriteTextToFile('/var/reports/people.csv', csv);Read, transform, and write a CSV file
ts
var raw = ReadTextFile('/var/inbox/data.csv');
var rows = ParseCSV(raw);
// Add a new column header and value
rows[0].push('Processed');
for (var i = 1; i < rows.length; i++) {
rows[i].push('yes');
}
WriteTextToFile('/var/outbox/data.csv', FormatCSV(rows));