std/csv provides CSV creation and serialization. new_doc creates a document with headers, add_row appends data rows, and stringify serializes to a CSV string. The module handles quoting, escaping, and custom delimiters. See recipe 18 for CSV parsing.
// CSV creation and serialization with std/csv // Creación y serialización CSV con std/csv import "std/csv" fn main() -> int { // Create a CSV document with headers let headers: Array = ["name", "age", "city"] let doc: CsvDoc = csv.new_doc(headers) // Add data rows csv.add_row(doc, ["Alice", "30", "Buenos Aires"]) csv.add_row(doc, ["Bob", "25", "New York"]) csv.add_row(doc, ["Charlie", "35", "London"]) // Serialize to CSV string let output: String = csv.stringify(doc) print(output) print("") // Parse it back let parsed: CsvDoc = csv.parse(output) let data: Array = csv.data_rows(parsed) print("rows: " + int_to_string(data.length())) print("cols: " + int_to_string(csv.col_count(parsed))) // Access by column name let row0: Array = data[0] let name: String = csv.get_by_name(parsed, row0, "city") print("first city: " + name) return 0 }
name,age,city Alice,30,Buenos Aires Bob,25,New York Charlie,35,London rows: 3 cols: 3 first city: Buenos Aires
How it works
csv.new_doc(headers) creates a CsvDoc struct with the first row set as headers. add_row appends a row (array of strings). stringify serializes the entire document, automatically escaping fields that contain commas, quotes, or newlines.
The round-trip works: parse reads the CSV string back into a CsvDoc, and get_by_name lets you access fields by column name instead of index. For TSV or other formats, use parse_with_delimiter and stringify_with_delimiter.