The standard librarySlide 51 of 85
51jsonThe standard library
JSON
hive.json treats a type declaration as the JSON schema itself. Neither of the two calls that do the work names a format: encode(value, codec) is a builtin, T.decode(text, codec) is the decoder a declaration derives, and what says JSON is the codec handed to them, hive.json.codec(). Another format is another codec in the same two places — hive.crypto.jwtCodec(secret), hive.net.queryParamsCodec(), hive.term.codec() — and a codec is an ordinary value, typed hive.codec.Codec<E> by the error 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 one is an error unless it has a
Default; aStr[3]has to be exactly three. - A number decodes into an
Intonly when it is written as one, so1.0does not; aFloatof3.0encodes as3. - A union is one key naming the variant,
{"Circle": {"radius": 5}}, a variant carrying nothing is{"Point": {}}, and anullpicks the type's first variant carrying nothing.T.Variant.decodereads one variant's payload, for a document whose variant you already know — sodecodecannot be a field's name. - A key written twice keeps its last value, and anything after the document but whitespace is an error. Text that is not JSON at all fails at
$, expecting "valid JSON". - A map and a
Tablehave no JSON; send their contents as a vector of a declared type. Nor has aSecret, which onlyrevealopens.
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}!"
}
}You can edit this program and run it here.Tab indents, Escape leaves the program, and Ctrl+Enter runs it.
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}"
}
}You can edit this program and run it here.Tab indents, Escape leaves the program, and Ctrl+Enter runs it.
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())
}You can edit this program and run it here.Tab indents, Escape leaves the program, and Ctrl+Enter runs it.
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
}
}You can edit this program and run it here.Tab indents, Escape leaves the program, and Ctrl+Enter runs it.