Nyx by Example

CSV Parsing

Comma-separated values are one of the most common data exchange formats. Nyx makes parsing them straightforward: split the text into lines with .split("\n"), then split each line into fields with .split(","). The std/csv import provides additional utilities for quoted fields and edge cases.

Code

// 18: CSV parsing — split lines and fields manually
import "std/csv"

fn main() -> int {
    let data: String = "name,age,city\nAlice,30,NYC\nBob,25,LA\nCharlie,35,SF"
    let rows: Array = data.split("\n")

    // Skip header, print each row parsed
    var i: int = 1
    while i < rows.length() {
        let row: String = rows[i]
        let fields: Array = row.split(",")
        let name: String = fields[0]
        let age: String = fields[1]
        let city: String = fields[2]
        print(name + " is " + age + " from " + city)
        i = i + 1
    }

    return 0
}

Output

Alice is 30 from NYC
Bob is 25 from LA
Charlie is 35 from SF

Explanation

.split(delimiter) is a built-in String method that splits a string at every occurrence of the given delimiter and returns an Array of String. Splitting on "\n" gives one element per CSV row; splitting each row on "," gives one element per field.

The loop starts at index 1 to skip the header row. This is a common idiom for CSV files where the first line contains column names rather than data. If you need to process the header (for example, to build a map of column name to index), you would read rows[0] separately before the loop.

This approach works well for simple CSV without quoted fields. For production CSV that may contain commas inside quoted strings or newlines inside fields, use the full parser from std/csv, which handles RFC 4180 quoting rules correctly.

← Previous Next →

Source: examples/by-example/18-csv.nx