Skip to content

Parsing CSV and TSV

Lanexio Parser handles CSV and TSV through a single package with configurable parsing. Both formats use the same never-throw parse path and produce zero-copy flat ASTs.

  1. Install the package.

    Terminal window
    pnpm add @lanexio/parser-grammar-csv
  2. Parse a CSV file.

    import { parseCsv } from '@lanexio/parser-grammar-csv';
    const encoder = new TextEncoder();
    const tree = parseCsv(encoder.encode('Name,Age,City\nAlice,30,NYC\nBob,25,LA'));
  3. Parse with options.

    import { parseCsv } from '@lanexio/parser-grammar-csv';
    const tree = parseCsv(encoder.encode('Name|Age|City\nAlice|30|NYC'), {
    delimiter: '|',
    header: true,
    });
import { parseTsv } from '@lanexio/parser-grammar-csv';
const tree = parseTsv(encoder.encode('Name\tAge\tCity\nAlice\t30\tNYC'));
OptionTypeDefaultDescription
delimiterstring','Field delimiter character
quotestring'"'Quote character for field escaping
headerbooleanfalseWhether the first record is a header row
skipEmptyLinesbooleanfalseWhether to skip empty lines

Each record is a CsvRecord node containing CsvField children. Fields in the header row carry CSV_FLAG_HEADER; quoted fields carry CSV_FLAG_QUOTED.

const cursor = tree.cursor();
cursor.gotoFirstChild(); // CsvRecord (first row)
cursor.gotoFirstChild(); // CsvField
console.log(cursor.current.kind); // CsvField kind id
console.log(cursor.current.flags); // CSV_FLAG_HEADER | CSV_FLAG_QUOTED