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

문서 검색

명세 6.0

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

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

    라이브러리

    std.json.parseAs

    Parses JSON text into a requested type.

    parseAs<T>(text: string) -> Result<T, string>
    수신자
    해당 없음
    최소 인자 수
    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.

    수신자

    매개변수 제약

    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.

    결과

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

    효과

    실패

    Result and effects

    링크

    Parse a complete JSON document before invoking the requested JSON decoder.

    Related entries

    링크

    std.json →

    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

    메뉴

    다운로드 →