Skip to content

CSV (std::csv)

std::csv reads and produces CSV text. Each row becomes an array of fields; parse_with_headers returns maps keyed by the header.

Parse

csv.parse(string) returns an array of arrays — the first row is treated like any other. csv.parse_with_headers uses the first row as keys:

Index-based access with parse and name-based access with parse_with_headers.

01-parse.zolo
Playground
// Feature: csv.parse — parses CSV into an array of arrays
// When to use: import spreadsheets, read CSV-formatted logs.

use std::csv

// Each line becomes an array; the result is an array of rows.
let raw = "name,age,active\nAlice,30,true\nBob,25,false"
let rows = csv.parse(raw)

print(rows[0][0])  // expected: name  (header)
print(rows[0][1])  // expected: age
print(rows[1][0])  // expected: Alice
print(rows[2][1])  // expected: 25

// With header: parse_with_headers returns an array of maps.
let people = csv.parse_with_headers(raw)
print(people[0]["name"])  // expected: Alice
print(people[0]["age"])  // expected: 30
print(people[1]["active"])  // expected: false

Special Field Escaping

Fields that contain commas must be quoted in CSV; embedded quotes are doubled (""). The parser handles these cases automatically:

Addresses with commas, nested quotes and empty fields.

02-escape.zolo
Playground
// Feature: csv.parse — fields with quotes, commas, and line breaks
// When to use: user data may contain special characters — double quotes
// escape inner quotes, and fields containing commas must be quoted.

use std::csv

// A field containing a comma must be quoted.
let raw1 = "name,address\nAlice,\"100 Main St, Apt 1\"\nBob,\"200 Oak Ave, Apt 2\""
let rows = csv.parse(raw1)
print(rows[1][1])  // expected: 100 Main St, Apt 1
print(rows[2][1])  // expected: 200 Oak Ave, Apt 2

// Double quotes inside a field: use "" to escape.
let raw2 = "msg\n\"she said \"\"hi\"\" yesterday\""
let rows2 = csv.parse(raw2)
print(rows2[1][0])  // expected: she said "hi" yesterday

// Empty fields become empty strings.
let raw3 = "a,b,c\n1,,3"
let rows3 = csv.parse(raw3)
print(rows3[1][1])  // expected: (empty)

Stringify

csv.stringify(rows) serialises an array of arrays into CSV text, automatically quoting fields that contain commas:

Round-trip: stringifyparse preserves fields with commas.

03-stringify.zolo
Playground
// Feature: csv.stringify — serializes an array of arrays into CSV
// When to use: export data to a spreadsheet, generate reports.

use std::csv

let rows = [
  ["name", "age", "city"],
  ["Alice", "30", "New York"],
  ["Bob", "25", "Austin, TX"],  // comma in field: csv quotes it automatically
  ["Carol", "40", "San Francisco"],
]

let out = csv.stringify(rows)
print(out)

// expected:
// name,age,city
// Alice,30,New York
// Bob,25,"Austin, TX"
// Carol,40,San Francisco

// Round-trip: stringify -> parse returns the same structure.
let parsed = csv.parse(out)
print(parsed[2][2])  // expected: Austin, TX
enespt-br