Nyx by Example

CSV Write

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.

Code

// CSV creation and serialization with std/csv

import "std/csv"

fn main() -> int {
    let headers: Array = ["name", "age", "city"]
    let doc: CsvDoc = csv.new_doc(headers)

    csv.add_row(doc, ["Alice", "30", "Buenos Aires"])
    csv.add_row(doc, ["Bob", "25", "New York"])
    csv.add_row(doc, ["Charlie", "35", "London"])

    let output: String = csv.stringify(doc)
    print(output)
    print("")

    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)))

    let row0: Array = data[0]
    let name: String = csv.get_by_name(parsed, row0, "city")
    print("first city: " + name)

    return 0
}

Output

name,age,city
Alice,30,Buenos Aires
Bob,25,New York
Charlie,35,London

rows: 3
cols: 3
first city: Buenos Aires

Explanation

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.

← Previous Next →

Source: examples/by-example/56-csv-write.nx