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

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

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

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

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

    Библиотека

    std.json.stringify

    Serializes a value as JSON text.

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

    Declaration and parameters

    Ссылка

    Доступность

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

    Import std.json in language mode 5.21.

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

    Получатель

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

    stringify requires the JSON conformance of its input type. It calls JSON.encode once and writes the returned JSON tree. A type without that conformance is rejected during checking with TPZ5533. The protocol representation rules define records, enums, arrays, maps, options, results and custom codecs.

    Successful output contains one compact JSON value with no leading whitespace or terminal newline. Object names follow the decoded key order. Arrays retain their element order. Map insertion order and record declaration order do not choose serialization order.

    The writer escapes quotation marks and backslashes. It uses the short escapes for LF, CR and tab. Other controls below U+0020 use four digit lowercase Unicode escapes. Other scalar values are emitted unchanged. It does not escape a slash or normalize Unicode.

    An existing JSONValue retains every accepted number lexeme. An int uses decimal digits and an optional minus. Float encoding follows JSON numeric conversion, including its shortest binary64 roundtrip spelling and negative zero. NaN and infinities return Err.

    The depth and active value cycle rules of JSON conversion apply. A depth above 128 or a value cycle returns an error beginning JSON_LIMIT. Other value failures return the selected codec error. Built in conversion errors identify the first failing child with a path rooted at $.

    The input expression is evaluated before conversion. Built in conversions visit arrays in index order and objects in sorted key order. A custom encoder retains its ordinary evaluation and side effects. An encoder error prevents writing. This function returns text and performs no filesystem or stream write.

    Результат

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

    Эффекты

    Ошибки

    Result and effects

    Ссылка

    Encode through the JSON protocol and return compact deterministic JSON text.

    Related entries

    Ссылка

    std.json →

    Serialize JSON in a deterministic order

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

    Serialize JSON in a deterministic order

    stringify requires the JSON conformance of its input type. It calls JSON.encode once and writes the returned JSON tree. A type without that conformance is rejected during checking with TPZ5533. The protocol representation rules define records, enums, arrays, maps, options, results and custom codecs.

    Successful output contains one compact JSON value with no leading whitespace or terminal newline. Object names follow the decoded key order. Arrays retain their element order. Map insertion order and record declaration order do not choose serialization order.

    The writer escapes quotation marks and backslashes. It uses the short escapes for LF, CR and tab. Other controls below U+0020 use four digit lowercase Unicode escapes. Other scalar values are emitted unchanged. It does not escape a slash or normalize Unicode.

    An existing JSONValue retains every accepted number lexeme. An int uses decimal digits and an optional minus. Float encoding follows JSON numeric conversion, including its shortest binary64 roundtrip spelling and negative zero. NaN and infinities return Err.

    The depth and active value cycle rules of JSON conversion apply. A depth above 128 or a value cycle returns an error beginning JSON_LIMIT. Other value failures return the selected codec error. Built in conversion errors identify the first failing child with a path rooted at $.

    The input expression is evaluated before conversion. Built in conversions visit arrays in index order and objects in sorted key order. A custom encoder retains its ordinary evaluation and side effects. An encoder error prevents writing. This function returns text and performs no filesystem or stream write.

    Причина

    Stable JSON bytes support fixtures and reproducible document inputs. The existing JSON conformance supplies one conversion path, while a Result distinguishes invalid values from successful text.

    Write sorted objects and preserve a parsed number lexeme

    Ссылка
    main.tpzWrite sorted objects and preserve a parsed number lexemeОткрыть песочницу →
    1. import std.json
    2. import std.test
    3. import std.io
    4. io.writeLine(test.assertOk(json.stringify(map { "z": 1, "a": 2 })))
    5. io.writeLine(test.assertOk(json.stringify(["a,b", "x\"y", "\n", "é"])))
    6. let number = test.assertOk(json.parse("1.2300e+03"))
    7. io.writeLine(test.assertOk(json.stringify(number)))
    8. let empty: Array<int> = []
    9. io.writeLine(test.assertOk(json.stringify(empty)))
    Ожидаемый выводКод завершения 0
    {"a":2,"z":1}
    ["a,b","x\"y","\n","é"]
    1.2300e+03
    []
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. {"a":2,"z":1}
    2. ["a,b","x\"y","\n","é"]
    3. 1.2300e+03
    4. []

    Write finite float values and reject a nonfinite value

    Ссылка
    main.tpzWrite finite float values and reject a nonfinite valueОткрыть песочницу →
    1. import std.json
    2. import std.io
    3. for value in ([1.5, -0.0]) {
    4. match (json.stringify(value)) {
    5. case Ok(text) => io.writeLine(text)
    6. case Err(_) => io.writeLine("rejected")
    7. }
    8. }
    9. match (json.stringify(0.0 / 0.0)) {
    10. case Ok(_) => io.writeLine("accepted")
    11. case Err(_) => io.writeLine("nonfinite rejected")
    12. }
    Ожидаемый выводКод завершения 0
    1.5
    -0
    nonfinite rejected
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. 1.5
    2. -0
    3. nonfinite rejected

    Меню

    Загрузка →