The standard librarySlide 53 of 85
53JsonThe standard library
A document with no declared shape
A document whose shape is not declared is a hive.json.JsonValue: an ordinary union with the variants String, Boolean, Int, Float, Array, Object and Null, taken apart with is like any other. Its codec is the document itself, so "x" reads as String("x") and writes back as "x", and null, wherever it sits, is Null().
- A number stays an
Intor aFloatthe way it was written, so1.0survives a round trip as1.0— though a whole number too big for anIntarrives as aFloat. - An
Objectholds its properties as ahive.map.Map<Str, JsonValue>in the order the document wrote them, sohive.map.getreads one by name; a key written twice keeps its first place and its last value. - A declared type may have a
JsonValuefield, leaving that part of an otherwise declared document open. - Holding a map, a
JsonValuehas no order of its own: sorting some takes a comparator.
A document with no declaration behind it
proc main(): void {
// Any document at all, taken apart like any union.
text := "\{\"name\":\"ada\",\"tags\":[\"x\",1]}"
if hive.json.JsonValue.decode(text, hive.json.codec()) is Result.Ok(doc) {
if doc is hive.json.JsonValue.Object(properties) {
if hive.map.get(properties, "name") is Result.Ok(name) && name is hive.json.JsonValue.String(value) {
echo value
}
}
}
// And one built by hand: an object's properties are a map.
mut hive.map.Map<Str, hive.json.JsonValue> fields = hive.map.new()
hive.map.set(fields, "count", hive.json.JsonValue.Int(3))
echo encode(hive.json.JsonValue.Object(fields), hive.json.codec())
}You can edit this program and run it here.Tab indents, Escape leaves the program, and Ctrl+Enter runs it.
null, and numbers as written
proc main(): void {
text := "\{\"a\": null, \"b\": [1, 1.0]}"
if hive.json.JsonValue.decode(text, hive.json.codec()) is Result.Ok(doc) {
echo encode(doc, hive.json.codec()) // the same document back
if doc is hive.json.JsonValue.Object(properties) {
if hive.map.get(properties, "a") is Result.Ok(a) && a is hive.json.JsonValue.Null {
echo "a is null"
}
}
}
}You can edit this program and run it here.Tab indents, Escape leaves the program, and Ctrl+Enter runs it.