Skip to content
Noodle
InstallLearnPlayground
GitHub

JSON

Json is a host-backed standard-library extern datatype. Programs construct and inspect it through the Json module rather than relying on JavaScript object representation.

The module provides constructors for every JSON shape:

func document() -> Json do
Json.object([
("name", Json.string("Noodle")),
("count", Json.int(3)),
("active", Json.bool(true)),
("tags", Json.array([Json.string("typed"), Json.string("modular")])),
("extra", Json.null()),
])
end

Json.number accepts Double; Json.int preserves the convenient explicit integer boundary. Object entries are supplied as an array of (String, Json) tuples.

Json.parse(text) returns Result[Json, String]; the error string describes invalid JSON input. Json.stringify(value) returns compact JSON text:

func normalize(text : String) -> Result[String, String] do
switch Json.parse(text)
case Result::Ok(value) then Result::Ok(Json.stringify(value))
case Result::Err(message) then Result::Err(message)
end
end

This example handles the Result explicitly. A throws wrapper can propagate a declared error type when the application wants a domain-specific failure contract.

Json is an extern datatype with six constructors: Null plus five @unboxed single-positional payloads (Bool, Num, Str, Arr, Obj). Matching classifies the host value with the recognize_json companion and binds the scrutinee value itself — no wrapper is allocated:

func describe(value : Json) -> String do
switch value
case Json::Null then "null"
case Json::Bool(flag) then flag.to_string()
case Json::Num(number) then number.to_string()
case Json::Str(text) then text
case Json::Arr(items) then
"array(" ++ items.length().to_string() ++ ")"
case Json::Obj(object) then
"object(" ++ object.entries().length().to_string() ++ ")"
end
end

JsonObject.field(name) returns Option[Json]; entries() returns the object’s entries as an array.

Next: Output, debugging, and tests.