Skip to content
Topaz6.0 · Before release
Download

Search documentation

Specification 6.0 · Not released · Tested product 5.21.3

Use arrow keys to choose a result. Press Enter to open.

Type an API name, diagnostic number, rule, or project topic.

    Library

    std.json

    Parse JSON, serialize values, and decode typed data.

    APIs in this module

    14 APIs

    NameModule
    JSONValue.asArraystd.json
    JSONValue.asBoolstd.json
    JSONValue.asIntstd.json
    JSONValue.asStringstd.json
    JSONValue.atstd.json
    JSONValue.getstd.json
    JSONValue.keysstd.json
    JSONValue.kindstd.json
    JSONValue.lengthstd.json
    JSONValue.numberTextstd.json
    JSONValue.valuesstd.json
    std.json.parsestd.json
    std.json.parseAsstd.json
    std.json.stringifystd.json

    Module

    Link

    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

    Link

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

    Availability

    Link

    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

    Link

    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

    Link

    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

    Link

    Read collection sizes, keys, and values as properties

    Link
    Ruletopaz.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.

    Why

    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.

    Source evidence

    Read the same properties on core collections

    Link
    main.tpzRead the same properties on core collectionsOpen in Playground
    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])
    Expected outputexit 0
    2:1:2
    name
    Topaz
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. 2:1:2
    2. name
    3. Topaz
    Source evidence

    Read a byte sequence size

    Link
    main.tpzRead a byte sequence sizeOpen in Playground
    1. import std.bytes { Bytes }
    2. import std.io
    3. let bytes = Bytes.empty()
    4. let size: int = bytes.length
    5. io.writeLine("{size}")
    Expected outputexit 0
    0
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. 0
    Source evidence

    Read a byte buffer size

    Link
    main.tpzRead a byte buffer sizeOpen in Playground
    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}")
    Expected outputexit 0
    3
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. 3
    Source evidence

    Read JSON sizes and preserve optional results

    Link
    main.tpzRead JSON sizes and preserve optional resultsOpen in Playground
    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")
    Expected outputexit 0
    JSON sizes read
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. JSON sizes read
    Source evidence

    Read JSON object keys

    Link
    main.tpzRead JSON object keysOpen in Playground
    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")
    Expected outputexit 0
    JSON keys read
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. JSON keys read
    Source evidence

    Read JSON object values

    Link
    main.tpzRead JSON object valuesOpen in Playground
    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")
    Expected outputexit 0
    JSON values read
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. JSON values read
    Source evidence

    Reject calling Bytes.length

    Link
    main.tpzReject calling Bytes.lengthOpen in Playground
    1. import std.bytes { Bytes }
    2. function inspect(value: Bytes) -> () {
    3. let result = value.length()
    4. return ()
    5. }
    Expected outputNonzero exit
    No stdout.
    $ topaz check main.tpz --format json · target product 5.21.3
    Expected result

    Expected result

    Rejection during check. Nonzero exit.

    • TPZ5005 stdlib-property-not-callable at main.tpz:3:22
    Source evidence

    Reject calling ByteBuffer.length

    Link
    main.tpzReject calling ByteBuffer.lengthOpen in Playground
    1. import std.bytes { ByteBuffer }
    2. function inspect(value: ByteBuffer) -> () {
    3. let result = value.length()
    4. return ()
    5. }
    Expected outputNonzero exit
    No stdout.
    $ topaz check main.tpz --format json · target product 5.21.3
    Expected result

    Expected result

    Rejection during check. Nonzero exit.

    • TPZ5005 stdlib-property-not-callable at main.tpz:3:22
    Source evidence

    Reject calling JSONValue.length

    Link
    main.tpzReject calling JSONValue.lengthOpen in Playground
    1. import std.json { JSONValue }
    2. function inspect(value: JSONValue) -> () {
    3. let result = value.length()
    4. return ()
    5. }
    Expected outputNonzero exit
    No stdout.
    $ topaz check main.tpz --format json · target product 5.21.3
    Expected result

    Expected result

    Rejection during check. Nonzero exit.

    • TPZ5005 stdlib-property-not-callable at main.tpz:3:22
    Source evidence

    Reject calling JSONValue.keys

    Link
    main.tpzReject calling JSONValue.keysOpen in Playground
    1. import std.json { JSONValue }
    2. function inspect(value: JSONValue) -> () {
    3. let result = value.keys()
    4. return ()
    5. }
    Expected outputNonzero exit
    No stdout.
    $ topaz check main.tpz --format json · target product 5.21.3
    Expected result

    Expected result

    Rejection during check. Nonzero exit.

    • TPZ5005 stdlib-property-not-callable at main.tpz:3:22
    Source evidence

    Reject calling JSONValue.values

    Link
    main.tpzReject calling JSONValue.valuesOpen in Playground
    1. import std.json { JSONValue }
    2. function inspect(value: JSONValue) -> () {
    3. let result = value.values()
    4. return ()
    5. }
    Expected outputNonzero exit
    No stdout.
    $ topaz check main.tpz --format json · target product 5.21.3
    Expected result

    Expected result

    Rejection during check. Nonzero exit.

    • TPZ5005 stdlib-property-not-callable at main.tpz:3:22
    Source evidence

    Diagnostics

    Link

    Value is not callable

    Inspect JSON kinds with kind

    Link
    Ruletopaz.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.

    Why

    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.

    Source evidence

    Distinguish null from every other JSON kind

    Link
    main.tpzDistinguish null from every other JSON kindOpen in Playground
    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. }
    Expected outputexit 0
    null:true
    bool:false
    number:false
    string:false
    array:false
    object:false
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. null:true
    2. bool:false
    3. number:false
    4. string:false
    5. array:false
    6. object:false
    Source evidence

    Keep present null values distinct from missing entries

    Link
    main.tpzKeep present null values distinct from missing entriesOpen in Playground
    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()}")
    Expected outputexit 0
    null:null
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. null:null
    Source evidence

    Reject the removed JSONValue.isNull member

    Link
    main.tpzReject the removed JSONValue.isNull memberOpen in Playground
    1. import std.json { JSONValue }
    2. function inspect(value: JSONValue) -> () {
    3. let result = value.isNull()
    4. return ()
    5. }
    Expected outputNonzero exit
    No stdout.
    $ topaz check main.tpz --format json · target product 5.21.3
    Expected result

    Expected result

    Rejection during check. Nonzero exit.

    • TPZ5006 stdlib-removed-member at main.tpz:4:22
    Source evidence

    Use kind to test a JSON value for null

    Link
    main.tpzUse kind to test a JSON value for nullOpen in Playground
    1. import std.json { JSONValue }
    2. function inspect(value: JSONValue) -> () {
    3. let result = value.kind() == "null"
    4. return ()
    5. }
    Expected outputexit 0
    No stdout.
    $ topaz check main.tpz --format json · target product 5.21.3
    Expected result

    Expected result

    Checking accepts the program. Exit code 0.

    Source evidence

    Diagnostics

    Link

    Unknown member or field

    Project JSON values without coercion

    Link
    Ruletopaz.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.

    Why

    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.

    Source evidence

    Inspect present values and missing children

    Link
    main.tpzInspect present values and missing childrenOpen in Playground
    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")
    Expected outputexit 0
    present values remain distinct from missing children
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. present values remain distinct from missing children
    Source evidence

    Keep integer projection within the declared spelling and range

    Link
    main.tpzKeep integer projection within the declared spelling and rangeOpen in Playground
    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. }
    Expected outputexit 0
    -9223372036854775808 = -9223372036854775808
    9223372036854775807 = 9223372036854775807
    9223372036854775808 = none
    -0 = 0
    1.0 = none
    1e0 = none
    1.5 = none
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. -9223372036854775808 = -9223372036854775808
    2. 9223372036854775807 = 9223372036854775807
    3. 9223372036854775808 = none
    4. -0 = 0
    5. 1.0 = none
    6. 1e0 = none
    7. 1.5 = none
    Source evidence

    Read matching keys and values in scalar order

    Link
    main.tpzRead matching keys and values in scalar orderOpen in Playground
    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)
    Expected outputexit 0
    a = null
    z = 1
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. a = null
    2. z = 1
    Source evidence

    Parse a complete JSON document

    Link
    Ruletopaz.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.

    Why

    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.

    Source evidence

    Retain numbers beyond binary and integer precision

    Link
    main.tpzRetain numbers beyond binary and integer precisionOpen in Playground
    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. }
    Expected outputexit 0
    9007199254740993
    9223372036854775808
    -0
    1.2300e+03
    1e9999
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. 9007199254740993
    2. 9223372036854775808
    3. -0
    4. 1.2300e+03
    5. 1e9999
    Source evidence

    Locate the first invalid scalar and end of input

    Link
    main.tpzLocate the first invalid scalar and end of inputOpen in Playground
    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. }
    Expected outputexit 0
    1,1
    1,6
    1,4
    1,4
    3,1
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. 1,1
    2. 1,6
    3. 1,4
    4. 1,4
    5. 3,1
    Source evidence

    Reject a repeated decoded key at its opening quote

    Link
    main.tpzReject a repeated decoded key at its opening quoteOpen in Playground
    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. }
    Expected outputexit 0
    1,8
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. 1,8
    Source evidence

    Decode surrogate pairs and reject malformed JSON spellings

    Link
    main.tpzDecode surrogate pairs and reject malformed JSON spellingsOpen in Playground
    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. }
    Expected outputexit 0
    invalid
    invalid
    invalid
    invalid
    invalid
    invalid
    invalid
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. invalid
    2. invalid
    3. invalid
    4. invalid
    5. invalid
    6. invalid
    7. invalid
    Source evidence

    Accept depth 128 and reject the next child

    Link
    main.tpzAccept depth 128 and reject the next childOpen in Playground
    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. }
    Expected outputexit 0
    depth 128 accepted
    depth 129 rejected
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. depth 128 accepted
    2. depth 129 rejected
    Source evidence

    Serialize JSON in a deterministic order

    Link
    Ruletopaz.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.

    Why

    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.

    Source evidence

    Write sorted objects and preserve a parsed number lexeme

    Link
    main.tpzWrite sorted objects and preserve a parsed number lexemeOpen in Playground
    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)))
    Expected outputexit 0
    {"a":2,"z":1}
    ["a,b","x\"y","\n","é"]
    1.2300e+03
    []
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. {"a":2,"z":1}
    2. ["a,b","x\"y","\n","é"]
    3. 1.2300e+03
    4. []
    Source evidence

    Write finite float values and reject a nonfinite value

    Link
    main.tpzWrite finite float values and reject a nonfinite valueOpen in Playground
    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. }
    Expected outputexit 0
    1.5
    -0
    nonfinite rejected
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. 1.5
    2. -0
    3. nonfinite rejected
    Source evidence

    Parse text before typed JSON decoding

    Link
    Ruletopaz.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.

    Why

    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.

    Source evidence

    Decode a record after parsing and report invalid data

    Link
    main.tpzDecode a record after parsing and report invalid dataOpen in Playground
    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. }
    Expected outputexit 0
    ink,7
    invalid data
    invalid data
    invalid data
    invalid data
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. ink,7
    2. invalid data
    3. invalid data
    4. invalid data
    5. invalid data
    Source evidence

    Call a custom decoder once after complete parsing

    Link
    main.tpzCall a custom decoder once after complete parsingOpen in Playground
    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. }
    Expected outputexit 0
    decode
    ink
    parse failed before decode
    
    $ topaz run main.tpz · target product 5.21.3
    Expected result

    Expected result

    Execution completes. Exit code 0.

    Expected stdout
    1. decode
    2. ink
    3. parse failed before decode
    Source evidence

    Menu

    Download