Skip to content
Topaz6.0 · Before release
Download

Search documentation

Specification 6.0 · Not released · Tested product 5.21.3

Use arrow keys to choose a result. Press Enter to open.

Type an API name, diagnostic number, rule, or project topic.

    Library

    std.csv

    Parse CSV text and serialize rows with or without headers.

    APIs in this module

    4 APIs

    NameModule
    std.csv.parsestd.csv
    std.csv.parseWithHeaderstd.csv
    std.csv.stringifystd.csv
    std.csv.stringifyWithHeaderstd.csv

    Module

    Link

    The module reads positional rows or associates data cells with unique header names. Positional parsing retains every column, including repeated text.

    Why

    Link

    Positional rows preserve every column, while named rows require a unique name for each column.

    Availability

    Link

    Import std.csv in language mode 5.21. The current compiler selects std/csv.tpz for this language mode. Availability in other released editions and inclusion in each installed distribution are Pending.

    Public API

    Link

    std.csv.parse

    std.csv.parseWithHeader

    std.csv.stringify

    std.csv.stringifyWithHeader

    Pending contracts

    Link

    Require unique headers for named CSV rows

    Link
    Ruletopaz.stdlib.contract.csv-unique-headers.rule

    Require unique headers for named CSV rows

    parseWithHeader returns Result<Array<Map<string, string>>, string>. A repeated header name returns Err instead of choosing a first or last column.

    Header uniqueness is checked before converting data rows. Repeated names are rejected when cell values are equal and when the input contains a header without data rows.

    The header names are the parsed CSV field values. Equality uses those string values without an additional trimming or case-folding step.

    Use csv.parse when columns must remain positional. Positional parsing preserves every field and does not assign header names.

    Why

    A named row gives each name one column. Rejecting duplicates keeps column order from selecting a winner, while positional parsing retains data that has no unique names.

    Source evidence

    Read unique named columns

    Link
    main.tpzRead unique named columnsOpen in Playground
    1. import std.csv
    2. import std.test
    3. import std.io
    4. let rows = test.assertOk(csv.parseWithHeader("name,count\nTopaz,6"))
    5. let row = test.assertSome(rows.get(0))
    6. io.writeLine(test.assertSome(row.get("name")))
    7. io.writeLine(test.assertSome(row.get("count")))
    Expected outputexit 0
    Topaz
    6
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. Topaz
    2. 6
    Source evidence

    Reject duplicate names

    Link
    main.tpzReject duplicate namesOpen in Playground
    1. import std.csv
    2. import std.io
    3. match (csv.parseWithHeader("name,name\nleft,right")) {
    4. case Err(_) => io.writeLine("duplicate headers rejected")
    5. case Ok(_) => io.writeLine("accepted")
    6. }
    Expected outputexit 0
    duplicate headers rejected
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. duplicate headers rejected

    The parser rejects this input by returning Err. The program handles that result and exits successfully.

    Source evidence

    Reject duplicate names after reversing values

    Link
    main.tpzReject duplicate names after reversing valuesOpen in Playground
    1. import std.csv
    2. import std.io
    3. match (csv.parseWithHeader("name,name\nright,left")) {
    4. case Err(_) => io.writeLine("duplicate headers rejected")
    5. case Ok(_) => io.writeLine("accepted")
    6. }
    Expected outputexit 0
    duplicate headers rejected
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. duplicate headers rejected

    The parser rejects this input by returning Err. The program handles that result and exits successfully.

    Source evidence

    Reject duplicate names even when the values agree

    Link
    main.tpzReject duplicate names even when the values agreeOpen in Playground
    1. import std.csv
    2. import std.io
    3. match (csv.parseWithHeader("name,name\nsame,same")) {
    4. case Err(_) => io.writeLine("duplicate headers rejected")
    5. case Ok(_) => io.writeLine("accepted")
    6. }
    Expected outputexit 0
    duplicate headers rejected
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. duplicate headers rejected

    The parser rejects this input by returning Err. The program handles that result and exits successfully.

    Source evidence

    Reject duplicate names before reading data rows

    Link
    main.tpzReject duplicate names before reading data rowsOpen in Playground
    1. import std.csv
    2. import std.io
    3. match (csv.parseWithHeader("name,name")) {
    4. case Err(_) => io.writeLine("duplicate headers rejected")
    5. case Ok(_) => io.writeLine("accepted")
    6. }
    Expected outputexit 0
    duplicate headers rejected
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. duplicate headers rejected

    The parser rejects this input by returning Err. The program handles that result and exits successfully.

    Source evidence

    Preserve repeated header text in positional rows

    Link
    main.tpzPreserve repeated header text in positional rowsOpen in Playground
    1. import std.csv
    2. import std.test
    3. import std.io
    4. let rows = test.assertOk(csv.parse("name,name\nleft,right"))
    5. let row = test.assertSome(rows.get(1))
    6. io.writeLine("{row[0]}:{row[1]}")
    Expected outputexit 0
    left:right
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. left:right
    Source evidence

    Serialize positional and named CSV rows

    Link
    Ruletopaz.stdlib.contract.csv-stringify.rule

    Serialize positional and named CSV rows

    stringify accepts arrays of string rows and returns text. It preserves row order and cell text. Rows may have different field counts. Commas separate fields and every row ends with LF, including the last row. An empty array of rows becomes empty text.

    A field containing a comma, quotation mark, CR or LF is enclosed in quotation marks. An embedded quotation mark is doubled. Embedded CR and LF remain inside the quoted field. A sole empty field is quoted to distinguish it from a row with no fields. Empty fields in a larger row need no quotation marks. Other whitespace and Unicode text remain unchanged.

    stringifyWithHeader(rows, columns) -> Result<string, string> writes a header using the supplied column names and then projects every map onto that ordered list. An absent key supplies an empty cell. Keys outside the list are ignored. A header is emitted even when there are no data rows.

    Column names use exact string equality. A repeated name, including a repeated empty name, returns a nonempty Err identifying that name and its zero based repeated index. Validation happens before row projection. A unique empty name is permitted. An empty column list writes an empty header row and one empty row for each input row.

    Positional serialization has no value error for a well typed input. Named serialization uses Result for invalid columns. Incorrect row or cell types follow ordinary checking diagnostics. Both functions evaluate supplied arguments once from left to right and perform no I/O or mutation. Their collection arguments follow value semantics.

    Named parsing and named writing require the same unique header names. Positional serialization remains available when a row has no naming schema. CSV parsing has its separate malformed input and field count rules.

    Why

    Explicit columns determine stable output without depending on map insertion order. Unique names prevent two fields from competing for one key. A Result reports invalid naming data through the same recoverable channel as named parsing.

    Source evidence

    Quote delimiters and line breaks and finish each record

    Link
    main.tpzQuote delimiters and line breaks and finish each recordOpen in Playground
    1. import std.csv
    2. import std.json
    3. import std.test
    4. import std.io
    5. let rows = [["name", "note"], ["a,b", "x\"y"], ["line\nnext", "carriage\rreturn"]]
    6. io.writeLine(test.assertOk(json.stringify(csv.stringify(rows))))
    Expected outputexit 0
    "name,note\n\"a,b\",\"x\"\"y\"\n\"line\nnext\",\"carriage\rreturn\"\n"
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. "name,note\n\"a,b\",\"x\"\"y\"\n\"line\nnext\",\"carriage\rreturn\"\n"
    Source evidence

    Distinguish no rows, no fields and one empty field

    Link
    main.tpzDistinguish no rows, no fields and one empty fieldOpen in Playground
    1. import std.csv
    2. import std.json
    3. import std.test
    4. import std.io
    5. let none: Array<Array<string>> = []
    6. let emptyRows: Array<Array<string>> = [[], [""]]
    7. io.writeLine(test.assertOk(json.stringify(csv.stringify(none))))
    8. io.writeLine(test.assertOk(json.stringify(csv.stringify(emptyRows))))
    Expected outputexit 0
    ""
    "\n\"\"\n"
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. ""
    2. "\n\"\"\n"
    Source evidence

    Choose output columns explicitly and fill absent cells

    Link
    main.tpzChoose output columns explicitly and fill absent cellsOpen in Playground
    1. import std.csv
    2. import std.json
    3. import std.test
    4. import std.io
    5. let rows = [map { "name": "Topaz", "extra": "ignored", "count": "6" }, map { "name": "Ink" }]
    6. let text = test.assertOk(csv.stringifyWithHeader(rows, ["count", "name"]))
    7. io.writeLine(test.assertOk(json.stringify(text)))
    8. let noRows: Array<Map<string, string>> = []
    9. io.writeLine(test.assertOk(json.stringify(test.assertOk(csv.stringifyWithHeader(noRows, ["name"])))))
    Expected outputexit 0
    "count,name\n6,Topaz\n,Ink\n"
    "name\n"
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. "count,name\n6,Topaz\n,Ink\n"
    2. "name\n"
    Source evidence

    Reject duplicate columns before serializing a row

    Link
    main.tpzReject duplicate columns before serializing a rowOpen in Playground
    1. import std.csv
    2. import std.io
    3. let rows: Array<Map<string, string>> = []
    4. match (csv.stringifyWithHeader(rows, ["name", "name"])) {
    5. case Ok(_) => io.writeLine("accepted")
    6. case Err(_) => io.writeLine("duplicate columns rejected")
    7. }
    Expected outputexit 0
    duplicate columns rejected
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. duplicate columns rejected
    Source evidence

    Menu

    Download