The standard librarySlide 51 of 86
51jsonThe standard library

JSON

hive.json treats a type declaration as the JSON schema. Two calls do the work, and neither names a format: the builtin encode(value, codec), and T.decode(text, codec), the decoder every declaration derives. The codec handed to them is what says JSON: hive.json.codec(). Another format is another codec in the same two places — hive.crypto.jwtCodec(secret), hive.net.queryParamsCodec(), hive.term.codec(). A codec is an ordinary value of type hive.codec.Codec<E>, where E is the error that decoding with it fails with.

Decoding answers with a Result<T, hive.json.JsonError> whose error carries the path that failed, what was expected and what was found. Encoding follows the static type, so it cannot fail. The rules:

  • Fields the type does not declare are ignored. A missing field is an error unless it has a Default. A Str[3] has to be exactly three.
  • A number decodes into an Int only when written as one, so 1.0 does not; a Float of 3.0 encodes as 3.
  • A union is one key naming the variant, {"Circle": {"radius": 5}}; a variant carrying nothing is {"Point": {}}; and a null picks the type's first variant carrying nothing. T.Variant.decode reads one variant's payload, for a document whose variant you already know — which is why decode cannot be a field's name.
  • A key written twice keeps its last value, and anything but whitespace after the document is an error. Text that is not JSON at all fails at $, expecting "valid JSON".
  • A map, a Table and a Secret have no JSON. Send a map's or a table's contents as a vector of a declared type; a Secret opens only with reveal.
The declaration is the schema, and the codec is the format
type Greeting { name: Str }

proc main(): void {
	body := encode(Greeting("ada"), hive.json.codec())
	echo body

	parsed := Greeting.decode(body, hive.json.codec())
	if parsed is Result.Ok(g) {
		echo "hello, {g.name}!"
	}
}
A document that does not fit says exactly where
type Greeting { name: Str  times: Int }

proc main(): void {
	if Greeting.decode("\{\"name\":\"ada\"}", hive.json.codec()) is Result.Error(why) {
		echo "{why.path}: expected {why.expected}, found {why.found}"
	}
}
A codec is a value
type Greeting { name: Str }

// Generic in the codec's error type, so one function writes every format.
func written(codec: hive.codec.Codec<E>): Str {
	return encode(Greeting("ada"), codec)
}

proc main(): void {
	asJson := hive.json.codec()
	echo written(asJson)
	echo written(hive.net.queryParamsCodec())
	echo written(hive.term.codec())
}
Unions, repeated keys, and what follows a document
type Shape {
	Circle { radius: Int }
	Point
}

type Greeting { name: Str }

proc main(): void {
	echo encode([Shape.Circle(5), Shape.Point()], hive.json.codec())
	if Shape.decode("null", hive.json.codec()) is Result.Ok(s) {
		echo s                                    // {} — the first variant carrying nothing
	}
	if Greeting.decode(`\{"name": "ada", "name": "grace"}`, hive.json.codec()) is Result.Ok(g) {
		echo g.name                               // grace — the last one wins
	}
	if Greeting.decode(`\{"name": "ada"} and more`, hive.json.codec()) is Result.Error(why) {
		echo why.expected                         // the end of the document
	}
}