JSON
Json is an opaque host-backed standard-library type. Programs construct and
inspect it through the Json module rather than relying on JavaScript object
representation.
Construct JSON values
Section titled “Construct JSON values”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()), ])endJson.number accepts Double; Json.int preserves the convenient explicit
integer boundary. Object entries are supplied as an array of (String, Json)
tuples.
Parse and stringify
Section titled “Parse and stringify”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) endendThis example handles the Result explicitly. A throws wrapper can propagate
a declared error type when the application wants a domain-specific failure
contract.
Inspect through JsonView
Section titled “Inspect through JsonView”JsonView presents the opaque host value as one of six datatype constructors:
Null, Bool, Num, Str, Arr, or Obj.
func describe(value : Json) -> String do switch value case Json.JsonView::Null then "null" case Json.JsonView::Bool(flag) then flag.to_string() case Json.JsonView::Num(number) then number.to_string() case Json.JsonView::Str(text) then text case Json.JsonView::Arr(items) then "array(" ++ items.length().to_string() ++ ")" case Json.JsonView::Obj(object) then "object(" ++ object.entries().length().to_string() ++ ")" endendThis is a view pattern: the associated IView provider converts the opaque
Json target once and the ordinary datatype pattern matches the resulting
shape. View pattern behavior builds on
Interfaces and extensions,
Advanced pattern matching for the complete
view-pattern rules.
JsonObject.field(name) returns Option[Json]; entries() returns the
object’s entries as an array.
Next: Output, debugging, and tests.