JSON and XML

JSON and XML

Both are auto-imported under their prefix.

JSON

[public] fn parse(text: string) => JsonValue
[public] fn serialize<T: impl Serialize>(value: T) => JsonValue
[public] fn stringify<T: impl Serialize>(value: T) => string
[public] fn read(text: string) => JsonDeserializer
[public] fn reader(root: JsonValue) => JsonDeserializer

The value tree is JsonValue with JsonNull, JsonBool, JsonNumber, JsonString, JsonArray, and JsonObject beneath it. Every node answers kind() with "null", "bool", "number", "string", "array", or "object", and to_string() renders it.

parse never fails. It assumes well-formed input, and malformed text yields whatever partial value was built. So check kind() before narrowing:

let value: json::JsonValue = json::parse(text)
if value.kind() != "object" {
    return None
}
let object: json::JsonObject = value as json::JsonObject
let found: json::JsonValue? = object.get("name")

JsonObject.get returns an optional. JsonArray.at returns a plain value and is unchecked. JsonObject is backed by IndexMap, so keys keep insertion order.

Building output by interpolation is common, and leaf strings must be escaped:

let name_json: string = new json::JsonString(name).to_string()
return `{"ok":true,"name":${name_json}}`

XML

xml::Element is a tag with attributes, ordered children, optional text, and event handlers. to_string() renders it, and equals compares structurally.

let node: xml::Element = new xml::Element("div")
node.set_attribute("class", "row")
node.set_text("hello")

Two limits worth knowing. There is no XML parser: the module builds, renders, and compares, but does not read XML. And attributes render in map order, which is unspecified, so output is not byte-stable across runs.