encoding/csv
Reading and writing CSV files, with correct quoting and conversion to a dynamic value.
import encoding.csv
CSV is the simplest table format: one row per line, fields separated by commas. A field containing a comma, a quote or a newline is wrapped in quotes, and a quote inside it is doubled. This package follows those rules both ways.
Every field is a string. When the first row is a header, ToValue turns each row into an object with those keys.
Types
CSVRow
struct CSVRow| Name | Type | Description |
|---|---|---|
fields | Vector | The row's fields. |
import encoding.csv
import encoding.value
func main:
text := "name,city\nAli,Tehran\n\"Sara, engineer\",\"Shiraz\"\n"
mut table := csv.ReadAll(text)
println table.rows.len()
each row in table.rows:
println row.fields.len(), row.fields[0]
end
println csv.WriteAll(table)
csv.FreeTable(table)
println csv.ReadLine(`a,"b,c",d`)
mut fields := Vector {} as Vector<str>
fields.push("plain")
fields.push(`with "quotes"`)
println csv.WriteLine(fields)
v := csv.ToValue("name,age\nAli,30\n")
println value.ArrayLen(v), value.AsString(value.ObjectGet(value.ArrayGet(v, 0), "name"))
println csv.FromValue(v)
opts := csv.CSVOptions { header = false }
rows := csv.ToValueWith("1,2\n3,4\n", opts)
println value.ArrayLen(rows), csv.FromValueWith(rows, opts)
endCSVTable
struct CSVTable| Name | Type | Description |
|---|---|---|
rows | Vector | The rows, including the header row. |
The example for this item is shown with the ones above: encoding-csv-Table.salam
CSVOptions
struct CSVOptions| Name | Type | Description |
|---|---|---|
header | bool = true | The first row is a header; true by default. When false, each row becomes an array. |
The example for this item is shown with the ones above: encoding-csv-Table.salam
Functions
ReadLine
func ReadLine(line: str): Vector<str>The example for this item is shown with the ones above: encoding-csv-Table.salam
WriteLine
func WriteLine(fields: Vector<str>): strThe example for this item is shown with the ones above: encoding-csv-Table.salam
ReadAll
func ReadAll(text: str): CSVTableThe example for this item is shown with the ones above: encoding-csv-Table.salam
FreeTable
func FreeTable(t &: CSVTable)The example for this item is shown with the ones above: encoding-csv-Table.salam
WriteAll
func WriteAll(table: CSVTable): strThe example for this item is shown with the ones above: encoding-csv-Table.salam
ToValueWith
func ToValueWith(text: str, opts: CSVOptions): value.ValueValue with the given options.The example for this item is shown with the ones above: encoding-csv-Table.salam
ToValue
func ToValue(text: str): value.ValueThe example for this item is shown with the ones above: encoding-csv-Table.salam
FromValueWith
func FromValueWith(v: value.Value, opts: CSVOptions): strThe example for this item is shown with the ones above: encoding-csv-Table.salam
FromValue
func FromValue(v: value.Value): strThe example for this item is shown with the ones above: encoding-csv-Table.salam