Grav v1.14.0

Csv

import "std/data" (included in import "std") · namespace std.data

Reading and writing CSV (comma-separated values), the plain-text table format that spreadsheets import and export. It follows RFC 4180: fields containing the separator, quotes or line breaks are wrapped in quotes, and a quote inside a field is written twice.

grav
import "std"

fn main() {
    let text = "name,city,note\nAda,London,\"likes \"\"math\"\"\"\nGrace,\"New York, NY\",\n"
    let rows = Csv.parse(text)
    print(rows.size())
    print(rows[2][1])

    for (person in Csv.parseRecords(text)) {
        print("${person["name"]} lives in ${person["city"]}")
    }

    let out: Array<Array<string>> = [["id", "label"], ["1", "plain"], ["2", "has, comma"]]
    print(Csv.format(out))
    print(Csv.parseWith("a;b\n1;2", ";"))
}
Output
3
New York, NY
Ada lives in London
Grace lives in New York, NY
id,label
1,plain
2,"has, comma"

[["a", "b"], ["1", "2"]]
  • parse returns every row as an Array<string>; parseRecords uses the first row as column names and returns one HashMap per following row.
  • Lines may end in \n or \r\n; a final blank line is ignored.
  • The ...With variants take another one-character separator, such as "\t" or ";".
  • A quoted field that is never closed throws ValueError.
  • To read a large CSV file line by line, remember that a quoted field may span lines; parsing whole files with parse is simplest.

API

class Csv

Parsing and formatting CSV text.

Static members

  • static fn parse(text: string) -> Array<Array<string>> — The rows of comma-separated text, each a list of fields. A blank last line is ignored. ValueError for a quote that is never closed.
  • static fn parseWith(text: string, sep: string) -> Array<Array<string>> — The rows of text with fields separated by sep (one character, such as "\t" or ";").
  • static fn parseRecords(text: string) -> Array<HashMap<string, string>> — The rows after the first, each as a map from the first row's column names to the row's values (missing fields are "").
  • static fn parseRecordsWith(text: string, sep: string) -> Array<HashMap<string, string>> — The same as parseRecords, with fields separated by sep.
  • static fn quote(field: string) -> string — One field, quoted when it contains the separator, a quote or a line break.
  • static fn quoteWith(field: string, sep: string) -> string — One field, quoted when it contains sep, a quote or a line break.
  • static fn formatRow(row: Array<string>) -> string — One row as a CSV line (without the line break).
  • static fn formatRowWith(row: Array<string>, sep: string) -> string — One row with fields separated by sep.
  • static fn format(rows: Array<Array<string>>) -> string — Rows as CSV text, each line ending in "\n".
  • static fn formatWith(rows: Array<Array<string>>, sep: string) -> string — Rows as text with fields separated by sep.

Edit this page on GitHub