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

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

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

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

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

    Библиотека

    std.json.parse

    Parses JSON text into a JSONValue.

    parse(text: string) -> Result<JSONValue, { column: int, line: int, message: 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.

    Получатель

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

    parse accepts one complete JSON value with leading and trailing space, tab, CR or LF. An empty input, a byte order mark, comments, trailing commas and trailing nonwhitespace return Err. Scalars are valid roots.

    JSON numbers follow the JSON decimal grammar. A leading plus, redundant leading zero, missing fraction or exponent digits, NaN and infinities are invalid. Every accepted lexeme is stored exactly without conversion to binary floating point. Its magnitude need not fit int or float.

    Quoted strings decode the JSON escapes and valid UTF 16 surrogate pairs into Unicode scalar values. Unescaped controls, malformed escapes and unpaired surrogates return Err. No Unicode normalization is performed.

    Object names are compared after escape decoding. A repeated name returns Err before its value is converted into the object. The second name does not overwrite the first. Arrays preserve source order and object traversal follows the decoded key order.

    The root starts at depth zero. Descending into an array element or object value adds one. Depths through 128 are accepted and the first value at depth 129 returns Err with a nesting limit message.

    A parse failure returns a record containing a nonempty cause message and one based line and column integers. Columns count Unicode scalar values. CRLF is one line break and a lone CR or LF also starts the next line. The first offending scalar is the location. An invalid escape points to its backslash. A repeated name points to its second opening quote. An incomplete input points immediately after the final scalar.

    The text expression is evaluated once before parsing. The parser consumes through trailing whitespace before returning Ok. It performs no I/O, invokes no typed decoder and exposes no partial tree. Malformed data uses the Result error channel rather than a runtime diagnostic.

    Результат

    The declared result type is Result<JSONValue, { column: int, line: int, message: string }>.

    Эффекты

    Ошибки

    Result and effects

    Ссылка

    Parse a complete JSON document without losing number text. Return a structured cause and scalar position for invalid input.

    Related entries

    Ссылка

    std.json →

    Parse a complete JSON document

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

    Parse a complete JSON document

    parse accepts one complete JSON value with leading and trailing space, tab, CR or LF. An empty input, a byte order mark, comments, trailing commas and trailing nonwhitespace return Err. Scalars are valid roots.

    JSON numbers follow the JSON decimal grammar. A leading plus, redundant leading zero, missing fraction or exponent digits, NaN and infinities are invalid. Every accepted lexeme is stored exactly without conversion to binary floating point. Its magnitude need not fit int or float.

    Quoted strings decode the JSON escapes and valid UTF 16 surrogate pairs into Unicode scalar values. Unescaped controls, malformed escapes and unpaired surrogates return Err. No Unicode normalization is performed.

    Object names are compared after escape decoding. A repeated name returns Err before its value is converted into the object. The second name does not overwrite the first. Arrays preserve source order and object traversal follows the decoded key order.

    The root starts at depth zero. Descending into an array element or object value adds one. Depths through 128 are accepted and the first value at depth 129 returns Err with a nesting limit message.

    A parse failure returns a record containing a nonempty cause message and one based line and column integers. Columns count Unicode scalar values. CRLF is one line break and a lone CR or LF also starts the next line. The first offending scalar is the location. An invalid escape points to its backslash. A repeated name points to its second opening quote. An incomplete input points immediately after the final scalar.

    The text expression is evaluated once before parsing. The parser consumes through trailing whitespace before returning Ok. It performs no I/O, invokes no typed decoder and exposes no partial tree. Malformed data uses the Result error channel rather than a runtime diagnostic.

    Причина

    Exact number storage avoids losing document data before a caller chooses a numeric type. Rejecting duplicate names prevents source order from silently selecting a value. A single scalar based location rule makes errors actionable across Unicode text and newline styles.

    Retain numbers beyond binary and integer precision

    Ссылка
    main.tpzRetain numbers beyond binary and integer precisionОткрыть песочницу →
    1. import std.json
    2. import std.test
    3. import std.io
    4. for text in (["9007199254740993", "9223372036854775808", "-0", "1.2300e+03", "1e9999"]) {
    5. let value = test.assertOk(json.parse(text))
    6. io.writeLine(test.assertSome(value.numberText()))
    7. }
    Ожидаемый выводКод завершения 0
    9007199254740993
    9223372036854775808
    -0
    1.2300e+03
    1e9999
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. 9007199254740993
    2. 9223372036854775808
    3. -0
    4. 1.2300e+03
    5. 1e9999

    Locate the first invalid scalar and end of input

    Ссылка
    main.tpzLocate the first invalid scalar and end of inputОткрыть песочницу →
    1. import std.json
    2. import std.io
    3. for text in (["", "true false", "[1,]", "[1 x]", "[\rtrue,\r?]"]) {
    4. match (json.parse(text)) {
    5. case Ok(_) => io.writeLine("accepted")
    6. case Err(error) => io.writeLine("{error.line},{error.column}")
    7. }
    8. }
    Ожидаемый выводКод завершения 0
    1,1
    1,6
    1,4
    1,4
    3,1
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. 1,1
    2. 1,6
    3. 1,4
    4. 1,4
    5. 3,1

    Reject a repeated decoded key at its opening quote

    Ссылка
    main.tpzReject a repeated decoded key at its opening quoteОткрыть песочницу →
    1. import std.json
    2. import std.io
    3. match (json.parse("\{\"a\":1,\"\\u0061\":2\}")) {
    4. case Ok(_) => io.writeLine("accepted")
    5. case Err(error) => io.writeLine("{error.line},{error.column}")
    6. }
    Ожидаемый выводКод завершения 0
    1,8
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

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

    Decode surrogate pairs and reject malformed JSON spellings

    Ссылка
    main.tpzDecode surrogate pairs and reject malformed JSON spellingsОткрыть песочницу →
    1. import std.json
    2. import std.test
    3. import std.io
    4. let value = test.assertOk(json.parse("\"\\uD83D\\uDE00\""))
    5. test.assertEq(test.assertSome(value.asString()), "😀")
    6. for text in (["01", "+1", "1.", "1e", "NaN", "\"\\uD800\"", "\"\\uDC00\""]) {
    7. match (json.parse(text)) {
    8. case Ok(_) => io.writeLine("accepted")
    9. case Err(_) => io.writeLine("invalid")
    10. }
    11. }
    Ожидаемый выводКод завершения 0
    invalid
    invalid
    invalid
    invalid
    invalid
    invalid
    invalid
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. invalid
    2. invalid
    3. invalid
    4. invalid
    5. invalid
    6. invalid
    7. invalid

    Accept depth 128 and reject the next child

    Ссылка
    main.tpzAccept depth 128 and reject the next childОткрыть песочницу →
    1. import std.json
    2. import std.io
    3. let mut text = "0"
    4. for level in (0 ..< 128) {
    5. text = "[" + text + "]"
    6. }
    7. match (json.parse(text)) {
    8. case Ok(_) => io.writeLine("depth 128 accepted")
    9. case Err(_) => io.writeLine("depth 128 rejected")
    10. }
    11. match (json.parse("[" + text + "]")) {
    12. case Ok(_) => io.writeLine("depth 129 accepted")
    13. case Err(_) => io.writeLine("depth 129 rejected")
    14. }
    Ожидаемый выводКод завершения 0
    depth 128 accepted
    depth 129 rejected
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. depth 128 accepted
    2. depth 129 rejected

    Меню

    Загрузка →