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

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

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

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

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

    Библиотека · std.json

    JSONValue.values

    Returns optional child values from this JSON value.

    values: Option<Array<JSONValue>>
    Модуль
    std.json →
    Получатель
    JSONValue
    Минимальное число аргументов
    0
    Максимальное число аргументов
    0

    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.

    Получатель

    JSONValue

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

    Bytes.length and ByteBuffer.length are read-only int properties that report the number of bytes.

    JSONValue.length is an Option<int> property. Arrays and objects return Some(count) for their element or member count. Other JSON kinds return None().

    JSONValue.keys and JSONValue.values are properties returning Option<Array<string>> and Option<Array<JSONValue>>. Objects return Some(keys) or Some(values). Other JSON kinds return None().

    Read these properties without parentheses, as with Array.length, Map.length, Map.keys, Map.values, and Set.length. Calling a property value is rejected as a non-callable value.

    JSONValue is an immutable JSON tree with the six JSON kinds. Reading a member preserves the tree.

    asBool and asString return Some for the matching kind and None() for every other kind. False and empty text are present values. Neither function parses text or converts a number.

    numberText returns the exact accepted number lexeme for a number and None() for another kind. It preserves a negative zero, exponent spelling and fractional trailing zeroes.

    asInt returns Some for a number spelled as an optional minus and decimal integer digits within the signed 64 bit range. Negative zero becomes zero. A decimal point, exponent, overflow or different kind returns None() without rounding.

    asArray returns the elements of an array in source order. Another kind returns None(). The returned array is a separate collection. Changing that collection does not change the JSON tree.

    at uses a zero based array index. A negative index, an index at or beyond the array length, or a receiver of another kind returns None(). get uses an exact decoded object key and returns None() for an absent key or another receiver kind. A present null child is Some containing JSON null.

    length is a property containing the array element count or object member count. Scalar kinds yield None(). keys and values are object properties. They contain arrays in ascending Unicode scalar order of decoded keys, with corresponding positions. Array and scalar receivers yield None() for both properties.

    The receiver and supplied arguments are evaluated once in ordinary call order. Inspection performs no I/O and invokes no user conversion. Incorrect argument types follow ordinary checking diagnostics rather than becoming absent values.

    Результат

    The declared result type is Option<Array<JSONValue>>.

    Эффекты

    Ошибки

    Result and effects

    Ссылка

    Select this field from a value of its named type without call parentheses.

    Read object children in the same order as the keys property.

    Collection observations use the same property syntax as Array, Map, and Set. Parentheses identify calls rather than stored or derived values.

    Related entries

    Ссылка

    std.json →

    Read collection sizes, keys, and values as properties

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

    Read collection sizes, keys, and values as properties

    Bytes.length and ByteBuffer.length are read-only int properties that report the number of bytes.

    JSONValue.length is an Option<int> property. Arrays and objects return Some(count) for their element or member count. Other JSON kinds return None().

    JSONValue.keys and JSONValue.values are properties returning Option<Array<string>> and Option<Array<JSONValue>>. Objects return Some(keys) or Some(values). Other JSON kinds return None().

    Read these properties without parentheses, as with Array.length, Map.length, Map.keys, Map.values, and Set.length. Calling a property value is rejected as a non-callable value.

    Причина

    The same collection observation should use the same syntax across core collections and library values. Keeping JSONValue results optional preserves its distinction between collections and scalar values.

    Read the same properties on core collections

    Ссылка
    main.tpzRead the same properties on core collectionsОткрыть песочницу →
    1. import std.io
    2. let array = [2, 3]
    3. let entries = map { "name": "Topaz" }
    4. let values = set { 2, 3 }
    5. io.writeLine("{array.length}:{entries.length}:{values.length}")
    6. io.writeLine(entries.keys[0])
    7. io.writeLine(entries.values[0])
    Ожидаемый выводКод завершения 0
    2:1:2
    name
    Topaz
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

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

    Read a byte sequence size

    Ссылка
    main.tpzRead a byte sequence sizeОткрыть песочницу →
    1. import std.bytes { Bytes }
    2. import std.io
    3. let bytes = Bytes.empty()
    4. let size: int = bytes.length
    5. io.writeLine("{size}")
    Ожидаемый выводКод завершения 0
    0
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

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

    Read a byte buffer size

    Ссылка
    main.tpzRead a byte buffer sizeОткрыть песочницу →
    1. import std.bytes { ByteBuffer }
    2. import std.io
    3. let buffer = ByteBuffer.allocate(3)
    4. let size: int = buffer.length
    5. io.writeLine("{size}")
    Ожидаемый выводКод завершения 0
    3
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

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

    Read JSON sizes and preserve optional results

    Ссылка
    main.tpzRead JSON sizes and preserve optional resultsОткрыть песочницу →
    1. import std.json
    2. import std.test
    3. import std.io
    4. let array = test.assertOk(json.parse("[1,2]"))
    5. let object = test.assertOk(json.parse("\{\"name\":\"Topaz\"\}"))
    6. let scalar = test.assertOk(json.parse("42"))
    7. let arraySize: Option<int> = array.length
    8. let objectSize: Option<int> = object.length
    9. let scalarSize: Option<int> = scalar.length
    10. test.assertEq(test.assertSome(arraySize), 2)
    11. test.assertEq(test.assertSome(objectSize), 1)
    12. test.assertNone(scalarSize)
    13. io.writeLine("JSON sizes read")
    Ожидаемый выводКод завершения 0
    JSON sizes read
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. JSON sizes read

    Read JSON object keys

    Ссылка
    main.tpzRead JSON object keysОткрыть песочницу →
    1. import std.json
    2. import std.test
    3. import std.io
    4. let object = test.assertOk(json.parse("\{\"name\":\"Topaz\"\}"))
    5. let array = test.assertOk(json.parse("[]"))
    6. let scalar = test.assertOk(json.parse("42"))
    7. let names: Option<Array<string>> = object.keys
    8. test.assertEq(test.assertSome(names)[0], "name")
    9. test.assertNone(array.keys)
    10. test.assertNone(scalar.keys)
    11. io.writeLine("JSON keys read")
    Ожидаемый выводКод завершения 0
    JSON keys read
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. JSON keys read

    Read JSON object values

    Ссылка
    main.tpzRead JSON object valuesОткрыть песочницу →
    1. import std.json
    2. import std.test
    3. import std.io
    4. let object = test.assertOk(json.parse("\{\"name\":\"Topaz\"\}"))
    5. let array = test.assertOk(json.parse("[]"))
    6. let scalar = test.assertOk(json.parse("42"))
    7. let values = test.assertSome(object.values)
    8. test.assertEq(test.assertSome(values[0].asString()), "Topaz")
    9. test.assertNone(array.values)
    10. test.assertNone(scalar.values)
    11. io.writeLine("JSON values read")
    Ожидаемый выводКод завершения 0
    JSON values read
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. JSON values read

    Reject calling Bytes.length

    Ссылка
    main.tpzReject calling Bytes.lengthОткрыть песочницу →
    1. import std.bytes { Bytes }
    2. function inspect(value: Bytes) -> () {
    3. let result = value.length()
    4. return ()
    5. }
    Ожидаемый выводНенулевой код завершения
    Нет стандартного вывода.
    $ topaz check main.tpz --format json · Целевой продукт 5.21.3
    Ожидаемый результат

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

    Этап отклонения check. Ненулевой код завершения.

    • TPZ5005 →

      stdlib-property-not-callable at main.tpz:3:22

    Reject calling ByteBuffer.length

    Ссылка
    main.tpzReject calling ByteBuffer.lengthОткрыть песочницу →
    1. import std.bytes { ByteBuffer }
    2. function inspect(value: ByteBuffer) -> () {
    3. let result = value.length()
    4. return ()
    5. }
    Ожидаемый выводНенулевой код завершения
    Нет стандартного вывода.
    $ topaz check main.tpz --format json · Целевой продукт 5.21.3
    Ожидаемый результат

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

    Этап отклонения check. Ненулевой код завершения.

    • TPZ5005 →

      stdlib-property-not-callable at main.tpz:3:22

    Reject calling JSONValue.length

    Ссылка
    main.tpzReject calling JSONValue.lengthОткрыть песочницу →
    1. import std.json { JSONValue }
    2. function inspect(value: JSONValue) -> () {
    3. let result = value.length()
    4. return ()
    5. }
    Ожидаемый выводНенулевой код завершения
    Нет стандартного вывода.
    $ topaz check main.tpz --format json · Целевой продукт 5.21.3
    Ожидаемый результат

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

    Этап отклонения check. Ненулевой код завершения.

    • TPZ5005 →

      stdlib-property-not-callable at main.tpz:3:22

    Reject calling JSONValue.keys

    Ссылка
    main.tpzReject calling JSONValue.keysОткрыть песочницу →
    1. import std.json { JSONValue }
    2. function inspect(value: JSONValue) -> () {
    3. let result = value.keys()
    4. return ()
    5. }
    Ожидаемый выводНенулевой код завершения
    Нет стандартного вывода.
    $ topaz check main.tpz --format json · Целевой продукт 5.21.3
    Ожидаемый результат

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

    Этап отклонения check. Ненулевой код завершения.

    • TPZ5005 →

      stdlib-property-not-callable at main.tpz:3:22

    Reject calling JSONValue.values

    Ссылка
    main.tpzReject calling JSONValue.valuesОткрыть песочницу →
    1. import std.json { JSONValue }
    2. function inspect(value: JSONValue) -> () {
    3. let result = value.values()
    4. return ()
    5. }
    Ожидаемый выводНенулевой код завершения
    Нет стандартного вывода.
    $ topaz check main.tpz --format json · Целевой продукт 5.21.3
    Ожидаемый результат

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

    Этап отклонения check. Ненулевой код завершения.

    • TPZ5005 →

      stdlib-property-not-callable at main.tpz:3:22

    Diagnostics

    Ссылка

    Value is not callable →

    Project JSON values without coercion

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

    Project JSON values without coercion

    JSONValue is an immutable JSON tree with the six JSON kinds. Reading a member preserves the tree.

    asBool and asString return Some for the matching kind and None() for every other kind. False and empty text are present values. Neither function parses text or converts a number.

    numberText returns the exact accepted number lexeme for a number and None() for another kind. It preserves a negative zero, exponent spelling and fractional trailing zeroes.

    asInt returns Some for a number spelled as an optional minus and decimal integer digits within the signed 64 bit range. Negative zero becomes zero. A decimal point, exponent, overflow or different kind returns None() without rounding.

    asArray returns the elements of an array in source order. Another kind returns None(). The returned array is a separate collection. Changing that collection does not change the JSON tree.

    at uses a zero based array index. A negative index, an index at or beyond the array length, or a receiver of another kind returns None(). get uses an exact decoded object key and returns None() for an absent key or another receiver kind. A present null child is Some containing JSON null.

    length is a property containing the array element count or object member count. Scalar kinds yield None(). keys and values are object properties. They contain arrays in ascending Unicode scalar order of decoded keys, with corresponding positions. Array and scalar receivers yield None() for both properties.

    The receiver and supplied arguments are evaluated once in ordinary call order. Inspection performs no I/O and invokes no user conversion. Incorrect argument types follow ordinary checking diagnostics rather than becoming absent values.

    Причина

    Optional projection keeps a missing child distinct from a stored null. Number text preserves the original representation, while the integer projection has an explicit spelling and range. Sorted key and value positions support deterministic traversal.

    Inspect present values and missing children

    Ссылка
    main.tpzInspect present values and missing childrenОткрыть песочницу →
    1. import std.json
    2. import std.test
    3. import std.io
    4. let value = test.assertOk(json.parse("[false,\"\",null,7]"))
    5. let items = test.assertSome(value.asArray())
    6. test.assertEq(test.assertSome(items[0].asBool()), false)
    7. test.assertEq(test.assertSome(items[1].asString()), "")
    8. test.assertEq(items[2].kind(), "null")
    9. test.assertEq(test.assertSome(items[3].asInt()), 7)
    10. test.assertNone(value.at(-1))
    11. test.assertNone(value.at(4))
    12. test.assertNone(value.get("0"))
    13. test.assertNone(items[0].asString())
    14. test.assertNone(items[1].numberText())
    15. test.assertNone(items[2].asArray())
    16. let object = test.assertOk(json.parse("\{\"present\":null\}"))
    17. test.assertEq(test.assertSome(object.get("present")).kind(), "null")
    18. test.assertNone(object.get("missing"))
    19. test.assertNone(object.at(0))
    20. io.writeLine("present values remain distinct from missing children")
    Ожидаемый выводКод завершения 0
    present values remain distinct from missing children
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. present values remain distinct from missing children

    Keep integer projection within the declared spelling and range

    Ссылка
    main.tpzKeep integer projection within the declared spelling and rangeОткрыть песочницу →
    1. import std.json
    2. import std.test
    3. import std.io
    4. for text in (["-9223372036854775808", "9223372036854775807", "9223372036854775808", "-0", "1.0", "1e0", "1.5"]) {
    5. let value = test.assertOk(json.parse(text))
    6. match (value.asInt()) {
    7. case Some(number) => io.writeLine("{text} = {number}")
    8. case None() => io.writeLine("{text} = none")
    9. }
    10. }
    Ожидаемый выводКод завершения 0
    -9223372036854775808 = -9223372036854775808
    9223372036854775807 = 9223372036854775807
    9223372036854775808 = none
    -0 = 0
    1.0 = none
    1e0 = none
    1.5 = none
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. -9223372036854775808 = -9223372036854775808
    2. 9223372036854775807 = 9223372036854775807
    3. 9223372036854775808 = none
    4. -0 = 0
    5. 1.0 = none
    6. 1e0 = none
    7. 1.5 = none

    Read matching keys and values in scalar order

    Ссылка
    main.tpzRead matching keys and values in scalar orderОткрыть песочницу →
    1. import std.json
    2. import std.test
    3. import std.io
    4. let object = test.assertOk(json.parse("\{\"z\":1,\"a\":null\}"))
    5. let names = test.assertSome(object.keys)
    6. let values = test.assertSome(object.values)
    7. test.assertEq(test.assertSome(object.length), 2)
    8. io.writeLine("{names[0]} = {values[0].kind()}")
    9. io.writeLine("{names[1]} = {test.assertSome(values[1].asInt())}")
    10. let array = test.assertOk(json.parse("[]"))
    11. test.assertEq(test.assertSome(array.length), 0)
    12. test.assertNone(array.keys)
    13. test.assertNone(array.values)
    14. let scalar = test.assertOk(json.parse("\"text\""))
    15. test.assertNone(scalar.length)
    Ожидаемый выводКод завершения 0
    a = null
    z = 1
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

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

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

    Ожидаемый стандартный вывод
    1. a = null
    2. z = 1

    Меню

    Загрузка →