JSON
JSON is a global object — available in every module with no import, like console and Math,
matching TypeScript. Because Zeus has no any type, a JSON document is modeled as an explicit
JsonValue tree (also global) rather than native objects.
let v: JsonValue = JSON.parse("{\"name\":\"zeus\",\"stars\":[1,2,3]}");console.log(v.get("name").asString()); // zeusconsole.log(v.get("stars").at(0).asInt()); // 1console.log(JSON.stringify(v)); // {"name":"zeus","stars":[1,2,3]}Reading a JsonValue
value.kind(): i32 // 0 null,1 bool,2 number,3 string,4 array,5 objectvalue.isNull() / isBool() / isNumber() / isString() / isArray() / isObject(): booleanvalue.asBool(): booleanvalue.asNumber(): f64value.asInt(): i32value.asString(): stringvalue.length(): i32 // array lengthvalue.at(index: i32): JsonValue // array elementvalue.has(key: string): boolean // objectvalue.get(key: string): JsonValue // object value, or JSON null if absentvalue.objectKeys(): string[]Building & writing
Since there is no any type, JSON.stringify serializes a JsonValue you build with the JSON.new*
factories (rather than an arbitrary native object):
let obj: JsonValue = JSON.newObject();obj.set("id", JSON.newNumber(42.0));let tags: JsonValue = JSON.newArray();tags.push(JSON.newString("cli"));obj.set("tags", tags);
console.log(JSON.stringify(obj)); // {"id":42,"tags":["cli"]}JSON.parse(text: string): JsonValueJSON.stringify(value: JsonValue): stringJSON.newObject(): JsonValueJSON.newArray(): JsonValueJSON.newString(s: string): JsonValueJSON.newNumber(n: f64): JsonValueJSON.newBool(b: boolean): JsonValueJSON.newNull(): JsonValuePlanned: typed, ergonomic access
The JsonValue tree API is deliberately explicit. Once generics and union types land, JSON
will gain a JS-like typed form so you can read fields directly instead of walking the tree:
// Planned — not yet availablelet v: JSONValue<{ name: string }> = JSON.parse(str);v.name; // typed field accessv["name"]; // or bracket accessTrack this on the roadmap.