The standard library
Slide 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 Int or a Float the way it was written, so 1.0 survives a round trip as 1.0 — though a whole number too big for an Int arrives as a Float.
  • An Object holds its properties as a hive.map.Map<Str, JsonValue> in the order the document wrote them, so hive.map.get reads one by name; a key written twice keeps its first place and its last value.
  • A declared type may have a JsonValue field, leaving that part of an otherwise declared document open.
  • Holding a map, a JsonValue has 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())
}
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"
			}
		}
	}
}