Skip to main content

44  json standard library

The json module provides an RFC 8259 JSON parser, a recursive json::Value DOM model, serializer utilities, and #param compile-time structural codecs (json::encode, json::encode_pretty, json::decode).

#use io
#use json

value = json::parse("[1, 2, 3]").expect("missing parse")
value [Array items] io::out(?items) | io::out("not an array")

44.1 Structural encoding and decoding (#param)

json provides compile-time structural codecs over records, tuples, enums, options (<P|>), arrays (E{}), slices (E[]), maps (K ^ V), primitives, and json::Value:

Function Signature Description
json::encode #param T: Type, T => String Serialize any value into a compact JSON string
json::encode_pretty #param T: Type, T, Int => String Serialize any value into an indented JSON string
json::decode #param T: Type, String => < T | Error > Parse JSON text and decode into target type T
json::to_value #param T: Type, T => Value Convert any typed value into a json::Value
json::from_value #param T: Type, Value => < T | Error > Decode a json::Value into target type T

44.1.1 Structural mapping conventions

  • Records ([(..)]): Encoded as JSON objects {...}. Decoding is forward-compatible: unknown keys in the input are ignored; missing keys use declared field defaults (f.default), <--> for option fields (<P|>), or #zero f.type for emptyable containers (E{}, K ^ V). An Error is returned when a required field is missing.
  • Positional tuples ([(..)] with unnamed fields): Encoded and decoded as fixed-length JSON arrays [...].
  • Enums ([<..>]) — External tagging: Unit variants (v.type [()]) encode and decode as JSON strings "VariantName"; payload variants encode and decode as single-key JSON objects {"VariantName": payload}.
  • Options ([<P|>]): <+ v +> encodes v; <--> encodes null. null or an omitted record field decodes to <-->.
#use io
#use json

#type User (
   name: String,
   role: String = "member",
   email: < String | >
)

u = User("Alice", "admin", <+ "alice@example.com" +>)
s = json::encode(u)
io::out(s)

decoded = json::decode(User, "{\"name\":\"Bob\"}").expect("missing decode")
io::out(decoded.name + ":" + decoded.role)

44.2 Value model & DOM helpers

Variant Payload
String String
Number Float
Boolean <>
Null unit
Array Value[]
Object (key: String, value: Value)[]

The module also exports growable arena types Values and Pairs, Result (< Value | Error >), and DOM inspection/serialization helpers:

Function Signature Description
json::parse String => < Value | Error > Parse a JSON string into a Value
json::stringify Value => String Serialize a Value into compact JSON
json::stringify_pretty Value, Int => String Serialize a Value with indentation
json::escape_string String => String Escape and quote a UTF-8 string as a JSON string literal
json::format_number Float => String Format a finite float as a JSON number (or "null" for NaN/Inf)
json::get Value, String => < Value | > Look up an object property by key
json::has Value, String => <> Return <+> if Value is an Object containing key
json::get_str Value, String => < String | > Extract a string property from an Object
json::get_int Value, String => < Int | > Extract an integer property from an Object
json::get_float Value, String => < Float | > Extract a numeric property from an Object
json::get_bool Value, String => < <> | > Extract a boolean property from an Object

44.3 Streaming pull scanner (json::Cursor)

For high-throughput structured logs or record extraction without building a json::Value DOM tree, json::Cursor scans keys and primitive values directly over the input String slice (json::cursor_read_str returns a zero-copy slice when no backslash escapes are present):

Function Signature Description
json::cursor String => Cursor Create a streaming Cursor at byte offset 0
json::cursor_reset Cursor, String => () Reuse an existing Cursor on a new JSON string
json::cursor_skip_ws Cursor => Int Advance past ASCII whitespace and return the new offset
json::cursor_eof Cursor => <> True when no non-whitespace bytes remain
json::cursor_peek Cursor => Int Next non-whitespace byte, or -1 at EOF
json::cursor_expect_byte Cursor, Int => <> Consume a specific non-whitespace ASCII byte
json::cursor_enter_object Cursor => <> Expect and consume {
json::cursor_enter_array Cursor => <> Expect and consume [
json::cursor_next_field Cursor => < String | > Read the next object field name and :, or consume closing } (<-->)
json::cursor_read_str Cursor => < String | > Parse a JSON string token (zero-copy slice when unescaped)
json::cursor_read_int Cursor => < Int | > Parse a signed JSON integer token directly without Float conversion
json::cursor_read_bool Cursor => < <> | > Parse true or false
json::cursor_skip_value Cursor => <> Skip any JSON value (scalar, string, nested array, or nested object)
#use io
#use json
#use str

cur = json::cursor("{\"id\":42,\"tags\":[\"a\",\"b\"],\"ok\":true}")
id' = 0
ok' = <->
json::cursor_enter_object(cur) |
   0.. @
      json::cursor_next_field(cur)
         | k =>
            k
               ["id"]
                  id' = json::cursor_read_int(cur) |_| 0
               ["ok"]
                  ok' = json::cursor_read_bool(cur) |_| <->
               |
                  json::cursor_skip_value(cur)
         | -->
io::out $ "${str::from_int(id')}:${ok' | "true" | "false"}"

44.4 Parsing and failure

parse: String => < Value | Error >

Malformed input produces the Error slot.

  • Recoverable inspection: Callers can inspect the error using named-branch pattern matching without aborting:
#use io
#use json

r = json::parse("malformed {")
r
   | val => io::out("Parsed successfully")
   | err => io::out(err.msg) // Recoverable: prints diagnostic message
  • Fatal extraction: .expect("reason") unwraps the successful value or aborts execution with a fatal diagnostic if an Error occurs:
#use json

// Aborts execution with code 400 if parsing fails:
val = json::parse(config_text).expect("missing parse")

44.5 Supported JSON features

The parser supports strings and escapes (including UTF-16 surrogate pairs for supplementary Unicode characters U+10000..U+10FFFF), numbers with optional sign, fraction, and exponent (1e-309 subnormals and compensated large exponents preserved), booleans, null, arrays, and objects. Arrays and objects are isolated per container. Strict JSON syntax is enforced: trailing commas, leading zeros in numbers, and trailing characters after the document root are rejected.

44.6 Parser state and concurrency contract

Each call to json::parse (and json::decode) allocates a private, instance-owned Scanner record (src, pos) with zero module-global mutable state: - Reentrancy: The parser is fully reentrant. Calling json::parse or json::decode while traversing or transforming another parsed Value (for example, decoding embedded JSON strings inside callbacks) is safe and isolated per invocation. - Threading: The parser is thread-safe across concurrent task::spawn workers. Concurrent parses do not share mutable global state, and all resulting Value nodes allocate in the calling thread’s ambient arena. - Validation: Raw string bytes are validated as strict UTF-8 (rejecting invalid lead or continuation bytes, overlong encodings, surrogate code points 0xD800–0xDFFF, and out-of-range scalars). Numbers preserve compensated decimal representations without intermediate overflow or underflow.