본문으로 건너뛰기
토파즈6.0 · 출시 전
다운로드 →

문서 검색

명세 6.0

방향키로 결과를 고르고 Enter를 눌러 여세요.

API 이름, 진단 번호, 규칙 또는 프로젝트 주제를 입력하세요.

    라이브러리

    std.json

    Parse JSON, serialize values, and decode typed data.

    이 모듈의 API

    14개 API

    이름모듈
    JSONValue.asArray →std.json →
    JSONValue.asBool →std.json →
    JSONValue.asInt →std.json →
    JSONValue.asString →std.json →
    JSONValue.at →std.json →
    JSONValue.get →std.json →
    JSONValue.keys →std.json →
    JSONValue.kind →std.json →
    JSONValue.length →std.json →
    JSONValue.numberText →std.json →
    JSONValue.values →std.json →
    std.json.parse →std.json →
    std.json.parseAs →std.json →
    std.json.stringify →std.json →

    Module

    링크

    JSONValue preserves exact number text and decoded JSON structure. Parse text with parse, encode values with stringify, and parse a requested type with parseAs. Decode an existing tree through the JSON protocol.

    Why

    링크

    Parsed JSON retains its value kinds before a caller chooses typed decoding.

    Availability

    링크

    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.

    Exported types

    링크

    export type JSONValue = JSONValue

    Type members keep the compiler-owned type name shown in their declarations. Importing a module does not create a new type identity.

    Public API

    링크

    std.json.parse →

    std.json.stringify →

    std.json.parseAs →

    JSONValue.asArray →

    JSONValue.asBool →

    JSONValue.asInt →

    JSONValue.asString →

    JSONValue.at →

    JSONValue.get →

    JSONValue.keys →

    JSONValue.kind →

    JSONValue.length →

    JSONValue.numberText →

    JSONValue.values →

    Pending contracts

    링크

    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. }
    기대 출력0이 아닌 종료 코드
    표준 출력 없음.
    $ topaz check main.tpz --format json · 대상 제품 5.21.3
    기대 결과

    기대 결과

    거절 단계 check. 종료 코드가 0이 아닙니다.

    • 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. }
    기대 출력0이 아닌 종료 코드
    표준 출력 없음.
    $ topaz check main.tpz --format json · 대상 제품 5.21.3
    기대 결과

    기대 결과

    거절 단계 check. 종료 코드가 0이 아닙니다.

    • 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. }
    기대 출력0이 아닌 종료 코드
    표준 출력 없음.
    $ topaz check main.tpz --format json · 대상 제품 5.21.3
    기대 결과

    기대 결과

    거절 단계 check. 종료 코드가 0이 아닙니다.

    • 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. }
    기대 출력0이 아닌 종료 코드
    표준 출력 없음.
    $ topaz check main.tpz --format json · 대상 제품 5.21.3
    기대 결과

    기대 결과

    거절 단계 check. 종료 코드가 0이 아닙니다.

    • 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. }
    기대 출력0이 아닌 종료 코드
    표준 출력 없음.
    $ topaz check main.tpz --format json · 대상 제품 5.21.3
    기대 결과

    기대 결과

    거절 단계 check. 종료 코드가 0이 아닙니다.

    • TPZ5005 →

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

    Diagnostics

    링크

    Value is not callable →

    Inspect JSON kinds with kind

    링크
    규칙topaz.stdlib.contract.json-kind.rule

    Inspect JSON kinds with kind

    JSONValue.kind() -> string returns exactly one of null, bool, number, string, array, or object. The name describes the JSON value's outermost kind. Both true and false have kind bool. Integer and fractional JSON numbers have kind number.

    Test whether a JSON value is null with value.kind() == "null". This comparison is false for false, zero, the empty string, and empty arrays and objects. Reading the kind does not modify or decode the JSON value.

    A present array element or object member containing JSON null is still present. at and get return Some(value) containing that JSONValue. An absent element or member returns None(). Inspect presence first, then compare the contained value's kind.

    JSONValue does not expose an isNull member. Use the same kind comparison for null as for every other JSON kind.

    이유

    One kind query distinguishes every JSON value kind. Comparing that result uses the ordinary equality rule for null, booleans, numbers, strings, arrays, and objects. A separate null predicate would duplicate one case and give it a second spelling. Keeping presence separate also prevents a stored null from being mistaken for a missing entry.

    Distinguish null from every other JSON kind

    링크
    main.tpzDistinguish null from every other JSON kind플레이그라운드 열기 →
    1. import std.json
    2. import std.test
    3. import std.io
    4. for source in (["null", "false", "0", "\"\"", "[]", "\{\}"]) {
    5. let value = test.assertOk(json.parse(source))
    6. let kind = value.kind()
    7. let nullKind = kind == "null"
    8. io.writeLine("{kind}:{nullKind}")
    9. }
    기대 출력종료 코드 0
    null:true
    bool:false
    number:false
    string:false
    array:false
    object:false
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. null:true
    2. bool:false
    3. number:false
    4. string:false
    5. array:false
    6. object:false

    Keep present null values distinct from missing entries

    링크
    main.tpzKeep present null values distinct from missing entries플레이그라운드 열기 →
    1. import std.json
    2. import std.test
    3. import std.io
    4. let array = test.assertOk(json.parse("[null]"))
    5. let object = test.assertOk(json.parse("\{\"present\":null\}"))
    6. let arrayValue = test.assertSome(array.at(0))
    7. let objectValue = test.assertSome(object.get("present"))
    8. test.assertNone(array.at(1))
    9. test.assertNone(object.get("absent"))
    10. io.writeLine("{arrayValue.kind()}:{objectValue.kind()}")
    기대 출력종료 코드 0
    null:null
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. null:null

    Reject the removed JSONValue.isNull member

    링크
    main.tpzReject the removed JSONValue.isNull member플레이그라운드 열기 →
    1. import std.json { JSONValue }
    2. function inspect(value: JSONValue) -> () {
    3. let result = value.isNull()
    4. return ()
    5. }
    기대 출력0이 아닌 종료 코드
    표준 출력 없음.
    $ topaz check main.tpz --format json · 대상 제품 5.21.3
    기대 결과

    기대 결과

    거절 단계 check. 종료 코드가 0이 아닙니다.

    Use kind to test a JSON value for null

    링크
    main.tpzUse kind to test a JSON value for null플레이그라운드 열기 →
    1. import std.json { JSONValue }
    2. function inspect(value: JSONValue) -> () {
    3. let result = value.kind() == "null"
    4. return ()
    5. }
    기대 출력종료 코드 0
    표준 출력 없음.
    $ topaz check main.tpz --format json · 대상 제품 5.21.3
    기대 결과

    기대 결과

    검사가 프로그램을 받아들입니다. 종료 코드 0.

    Diagnostics

    링크

    Unknown member or field →

    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

    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

    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

    Parse text before typed JSON decoding

    링크
    규칙topaz.stdlib.contract.json-parse-as.rule

    Parse text before typed JSON decoding

    parseAs<T> requires an explicit JSON decodable result type. The ordinary JSON capability checks apply. Omitting a required result type or selecting a type without decoding support produces TPZ5534.

    The function completes JSON parsing before calling JSON.decode<T>. A malformed document returns an error string containing the parse cause, line and column. It never calls the decoder on a malformed or trailing input.

    After parsing succeeds, the selected decoder is called once. Its Ok payload or Err message becomes the result. Custom decoder effects occur after parsing and follow ordinary function evaluation. Built in decoding performs no I/O.

    The JSON protocol defines supported representations. Derived records ignore unknown fields and use declared defaults for missing fields. A missing required field, wrong kind, unknown enum tag, wrong payload count or value outside the target numeric range returns Err. No string to number or string to boolean coercion is performed.

    Built in errors describe the expected shape and first failing path rooted at $. Arrays are checked in increasing index order and object fields in ascending Unicode scalar order. Built in int decoding requires an exactly integral value within signed 64 bit bounds. Float decoding follows the protocol rounding and overflow rules. Optional null and nested option normalization follow the same protocol rule as JSON.decode. Use numberText and asInt when the input must retain the integer spelling boundary.

    Decode an already parsed tree with JSON.decode<T>. There is no second JSONValue receiver decoding form. Parsing failure and decoding failure are recoverable Result errors and do not produce assertion diagnostics by themselves.

    이유

    Parsing and decoding are separate boundaries. A complete syntax check prevents a user decoder from acting on malformed input, and one protocol dispatch keeps text and tree conversion consistent.

    Decode a record after parsing and report invalid data

    링크
    main.tpzDecode a record after parsing and report invalid data플레이그라운드 열기 →
    1. import std.json
    2. import std.test
    3. import std.io
    4. record Item derives JSON { name: string, count: int = 7 }
    5. let item = test.assertOk(json.parseAs<Item>("\{\"name\":\"ink\",\"extra\":true\}"))
    6. io.writeLine("{item.name},{item.count}")
    7. for text in (["\{\}", "17", "[", "\{\"name\":\"ink\",\"count\":9223372036854775808\}"]) {
    8. match (json.parseAs<Item>(text)) {
    9. case Ok(_) => io.writeLine("accepted")
    10. case Err(_) => io.writeLine("invalid data")
    11. }
    12. }
    기대 출력종료 코드 0
    ink,7
    invalid data
    invalid data
    invalid data
    invalid data
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. ink,7
    2. invalid data
    3. invalid data
    4. invalid data
    5. invalid data

    Call a custom decoder once after complete parsing

    링크
    main.tpzCall a custom decoder once after complete parsing플레이그라운드 열기 →
    1. import std.json { JSONValue, parseAs }
    2. import std.io
    3. record Token { text: string }
    4. impl JSON<Token> {
    5. function encode(value: Token) -> Result<JSONValue, string> {
    6. JSON.encode(value.text)
    7. }
    8. function decode(value: JSONValue) -> Result<Token, string> {
    9. io.writeLine("decode")
    10. match (value.asString()) {
    11. case Some(text) => Ok(Token { text: text })
    12. case None() => Err("expected token string")
    13. }
    14. }
    15. }
    16. match (parseAs<Token>("\"ink\"")) {
    17. case Ok(value) => io.writeLine(value.text)
    18. case Err(message) => io.writeLine(message)
    19. }
    20. match (parseAs<Token>("\"ink\" false")) {
    21. case Ok(_) => io.writeLine("accepted")
    22. case Err(_) => io.writeLine("parse failed before decode")
    23. }
    기대 출력종료 코드 0
    decode
    ink
    parse failed before decode
    
    $ topaz run main.tpz · 대상 제품 5.21.3
    기대 결과

    기대 결과

    실행을 마칩니다. 종료 코드 0.

    기대 표준 출력
    1. decode
    2. ink
    3. parse failed before decode

    메뉴

    다운로드 →