Перейти к содержимому
Топаз6.0 · До релиза
Загрузка →

Поиск в документации

Спецификация 6.0

Выберите результат стрелками и нажмите Enter, чтобы открыть его.

Введите имя API, номер диагностики, правило или тему проекта.

    Библиотека

    std.csv.stringifyWithHeader

    Serializes named rows using a supplied column list.

    stringifyWithHeader(rows: Array<Map<string, string>>, columns: Array<string>) -> Result<string, string>
    Модуль
    std.csv →
    Получатель
    Неприменимо
    Минимальное число аргументов
    2
    Максимальное число аргументов
    2

    Declaration and parameters

    Ссылка

    Доступность

    Включено по умолчанию · Не определено

    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.

    Получатель

    Ограничения параметров

    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.

    Результат

    The declared result type is Result<string, string>.

    Эффекты

    Ошибки

    Result and effects

    Ссылка

    Validate unique column names and serialize named rows in the supplied column order.

    Related entries

    Ссылка

    std.csv →

    Serialize positional and named CSV rows

    Ссылка
    Правилоtopaz.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.

    Причина

    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.

    Quote delimiters and line breaks and finish each record

    Ссылка
    main.tpzQuote delimiters and line breaks and finish each recordОткрыть песочницу →
    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))))
    Ожидаемый выводКод завершения 0
    "name,note\n\"a,b\",\"x\"\"y\"\n\"line\nnext\",\"carriage\rreturn\"\n"
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. "name,note\n\"a,b\",\"x\"\"y\"\n\"line\nnext\",\"carriage\rreturn\"\n"

    Distinguish no rows, no fields and one empty field

    Ссылка
    main.tpzDistinguish no rows, no fields and one empty fieldОткрыть песочницу →
    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))))
    Ожидаемый выводКод завершения 0
    ""
    "\n\"\"\n"
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. ""
    2. "\n\"\"\n"

    Choose output columns explicitly and fill absent cells

    Ссылка
    main.tpzChoose output columns explicitly and fill absent cellsОткрыть песочницу →
    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"])))))
    Ожидаемый выводКод завершения 0
    "count,name\n6,Topaz\n,Ink\n"
    "name\n"
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. "count,name\n6,Topaz\n,Ink\n"
    2. "name\n"

    Reject duplicate columns before serializing a row

    Ссылка
    main.tpzReject duplicate columns before serializing a rowОткрыть песочницу →
    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. }
    Ожидаемый выводКод завершения 0
    duplicate columns rejected
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. duplicate columns rejected

    Меню

    Загрузка →