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

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

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

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

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

    Библиотека

    std.toml.fromJson

    Converts a JSONValue into a TOMLValue.

    fromJson(value: JSONValue) -> Result<TOMLValue, string>
    Модуль
    std.toml →
    Получатель
    Неприменимо
    Минимальное число аргументов
    1
    Максимальное число аргументов
    1

    Declaration and parameters

    Ссылка

    Доступность

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

    Import std.toml in language mode 5.21.

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

    Получатель

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

    fromJson recursively converts a JSONValue into a TOMLValue and returns Result<TOMLValue, string>. Booleans, strings, arrays and objects retain their values and structure. JSON null has no TOML representation and returns Err, including a nested null.

    An integer lexeme must fit signed 64 bit and becomes a TOML integer. An out of range integer returns Err rather than changing into a float. A fractional or exponent lexeme becomes binary64 with nearest ties to even rounding. Overflow to infinity returns Err. Finite rounding and underflow may change the exact decimal value.

    A string is kept as a string even when it resembles a date or time. Converting a JSON scalar or array is permitted, but writing it as a complete TOML document still requires a root table.

    TOMLValue.toJson() -> Result<JSONValue, string> recursively converts a TOML value. Tables become objects and arrays retain order. Finite numbers follow JSON numeric conversion. Nonfinite numbers return Err rather than becoming a string or null.

    TOML dates and times become strings in the normalized TOML spelling used by the writer. This conversion loses their TOML kind. JSON also does not distinguish an integer from an integral float. A reverse conversion therefore need not restore the original TOML kinds. Comments and source number spellings are not preserved.

    Both conversions visit array elements by index and object or table keys in the decoded key order. They stop at the first unrepresentable child. The nonempty error identifies its path rooted at $ and its cause. Inputs remain unchanged and neither conversion performs I/O.

    Результат

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

    Эффекты

    Ошибки

    Result and effects

    Ссылка

    Convert JSON recursively and return an error for null or an unrepresentable number.

    Related entries

    Ссылка

    std.toml →

    Convert TOML and JSON with explicit failures

    Ссылка
    Правилоtopaz.stdlib.contract.toml-json.rule

    Convert TOML and JSON with explicit failures

    fromJson recursively converts a JSONValue into a TOMLValue and returns Result<TOMLValue, string>. Booleans, strings, arrays and objects retain their values and structure. JSON null has no TOML representation and returns Err, including a nested null.

    An integer lexeme must fit signed 64 bit and becomes a TOML integer. An out of range integer returns Err rather than changing into a float. A fractional or exponent lexeme becomes binary64 with nearest ties to even rounding. Overflow to infinity returns Err. Finite rounding and underflow may change the exact decimal value.

    A string is kept as a string even when it resembles a date or time. Converting a JSON scalar or array is permitted, but writing it as a complete TOML document still requires a root table.

    TOMLValue.toJson() -> Result<JSONValue, string> recursively converts a TOML value. Tables become objects and arrays retain order. Finite numbers follow JSON numeric conversion. Nonfinite numbers return Err rather than becoming a string or null.

    TOML dates and times become strings in the normalized TOML spelling used by the writer. This conversion loses their TOML kind. JSON also does not distinguish an integer from an integral float. A reverse conversion therefore need not restore the original TOML kinds. Comments and source number spellings are not preserved.

    Both conversions visit array elements by index and object or table keys in the decoded key order. They stop at the first unrepresentable child. The nonempty error identifies its path rooted at $ and its cause. Inputs remain unchanged and neither conversion performs I/O.

    Причина

    A format conversion must expose values that its destination cannot represent. A Result keeps nonfinite failure explicit and avoids inventing a second conversion function or silently changing a numeric value into another kind.

    Reject null and out of range integer conversion

    Ссылка
    main.tpzReject null and out of range integer conversionОткрыть песочницу →
    1. import std.json
    2. import std.toml
    3. import std.test
    4. import std.io
    5. for text in (["null", "9223372036854775808", "1e9999"]) {
    6. let value = test.assertOk(json.parse(text))
    7. match (toml.fromJson(value)) {
    8. case Ok(_) => io.writeLine("accepted")
    9. case Err(_) => io.writeLine("unrepresentable")
    10. }
    11. }
    Ожидаемый выводКод завершения 0
    unrepresentable
    unrepresentable
    unrepresentable
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. unrepresentable
    2. unrepresentable
    3. unrepresentable

    Identify the first unrepresentable child

    Ссылка
    main.tpzIdentify the first unrepresentable childОткрыть песочницу →
    1. import std.json
    2. import std.toml
    3. import std.test
    4. import std.io
    5. let value = test.assertOk(json.parse("\{\"x\":[null]\}"))
    6. let error = test.assertErr(toml.fromJson(value))
    7. test.assertContains(error, "$.x[0]")
    8. io.writeLine("child located")
    Ожидаемый выводКод завершения 0
    child located
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. child located

    Convert a TOML table through a recoverable JSON result

    Ссылка
    main.tpzConvert a TOML table through a recoverable JSON resultОткрыть песочницу →
    1. import std.json
    2. import std.toml
    3. import std.test
    4. import std.io
    5. let value = test.assertOk(toml.parse("name = \"Topaz\"\ncount = 6\n"))
    6. let tree = test.assertOk(value.toJson())
    7. io.writeLine(test.assertOk(json.stringify(tree)))
    8. let restored = test.assertOk(toml.fromJson(tree))
    9. io.writeLine(test.assertOk(toml.stringify(restored)))
    Ожидаемый выводКод завершения 0
    {"count":6,"name":"Topaz"}
    count = 6
    name = "Topaz"
    
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. {"count":6,"name":"Topaz"}
    2. count = 6
    3. name = "Topaz"

    Return an error for a TOML infinity during JSON conversion

    Ссылка
    main.tpzReturn an error for a TOML infinity during JSON conversionОткрыть песочницу →
    1. import std.toml
    2. import std.test
    3. import std.io
    4. let value = test.assertOk(toml.parse("value = inf\n"))
    5. match (value.toJson()) {
    6. case Ok(_) => io.writeLine("accepted")
    7. case Err(_) => io.writeLine("nonfinite rejected")
    8. }
    Ожидаемый выводКод завершения 0
    nonfinite rejected
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

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

    Меню

    Загрузка →