Capstone 1: the value type

Go has no sum types, so a JSON value is a struct with a kind and one field per kind: a bool, a number, a string, a slice of values and a map of values with sorted keys. The kind decides which field is valid. The type is small, it never panics on a bad access, and it is the one thing the parser, the writer and the command line tool all share.

Kinds and the struct

ValueKind is an integer per kind with a String method. The struct keeps every representation side by side and the kind as the discriminator; the memory cost of the unused fields is the price of a type that needs no interface and no allocation per value.

type ValueKind int const ( NullKind ValueKind = iota BoolKind NumberKind StringKind ArrayKind ObjectKind ) // String names a ValueKind. func (k ValueKind) String() string { switch k { case NullKind: return "null" case BoolKind: return "bool" case NumberKind: return "number" case StringKind: return "string" case ArrayKind: return "array" case ObjectKind: return "object" default: return "invalid" } } // Value is one JSON value: null, a bool, a number, a string, an array or an object. type Value struct { kind ValueKind b bool n float64 s string arr []Value obj map[string]Value keys []string }

The struct is unexported inside and exported as a value, so a program constructs one through the functions and reads it through the methods; there is no way to set the number of a string value. That is the invariant the kind field protects, and every method below checks it before it reads a field.

Constructors

Six functions build the six kinds. ObjectValue sorts the keys once, which makes the encoding stable and the key list cheap to copy. ArrayValue keeps the slice it is given; a caller that reuses the slice after constructing a value shares it, which is the one ownership rule of the type.

func NullValue() Value { return Value{kind: NullKind} } // Bool returns a boolean value. func BoolValue(b bool) Value { return Value{kind: BoolKind, b: b} } // Number returns a number value. func NumberValue(n float64) Value { return Value{kind: NumberKind, n: n} } // String returns a string value. func StringValue(s string) Value { return Value{kind: StringKind, s: s} } // Array returns an array value. func ArrayValue(items []Value) Value { return Value{kind: ArrayKind, arr: items} } // Object returns an object value. The keys are kept in sorted order. func ObjectValue(fields map[string]Value) Value { keys := make([]string, 0, len(fields)) for k := range fields { keys = append(keys, k) } sort.Strings(keys) return Value{kind: ObjectKind, obj: fields, keys: keys} }

The constructors are the whole API for writing a value by hand, which the command line tool does not use but a test does. A JSON builder in a program that generates documents starts here, and the writer of the next lesson turns the result into bytes.

Accessors that never panic

Each accessor returns the zero value when the kind is wrong: Float of a string is zero, Index of an object is null, Get of an array is null and false. A program that reads a foreign document checks the kind once and then uses the accessors freely, and a test that expects a panic has to look for one in vain.

func (v Value) Kind() ValueKind { return v.kind } // Bool returns the boolean of a bool value, or false. func (v Value) Bool() bool { return v.b } // Float returns the number of a number value, or 0. func (v Value) Float() float64 { return v.n } // Str returns the string of a string value, or "". func (v Value) Str() string { return v.s } // Len returns the number of items of an array or the fields of an object. func (v Value) Len() int { switch v.kind { case ArrayKind: return len(v.arr) case ObjectKind: return len(v.obj) default: return 0 } } // Index returns the i-th item of an array, or a null value. func (v Value) Index(i int) Value { if v.kind != ArrayKind || i < 0 || i >= len(v.arr) { return NullValue() } return v.arr[i] } // Get returns the field of an object and whether it exists. func (v Value) Get(key string) (Value, bool) { if v.kind != ObjectKind { return NullValue(), false } field, ok := v.obj[key] return field, ok } // Keys returns the keys of an object in sorted order. func (v Value) Keys() []string { out := make([]string, len(v.keys)) copy(out, v.keys) return out } // Array returns the items of an array value. func (v Value) Array() []Value { out := make([]Value, len(v.arr)) copy(out, v.arr) return out }

Len, Index and Get cover the two containers, and Keys and Array return copies so a caller cannot reorder the internals. Str, Float and Bool are the scalars; a missing field and a JSON null are both NullKind here, and a program that must tell them apart uses the ok from Get.

The demo

The command builds a note with all six kinds, prints its keys and reads the title, the tags and a field that does not exist. The output is the real run.

package main import ( "fmt" "example.com/jsonx/jsonx" ) func main() { note := jsonx.ObjectValue(map[string]jsonx.Value{ "id": jsonx.NumberValue(1), "title": jsonx.StringValue("buy milk"), "done": jsonx.BoolValue(false), "tags": jsonx.ArrayValue([]jsonx.Value{jsonx.StringValue("home"), jsonx.StringValue("errand")}), "note": jsonx.NullValue(), }) fmt.Println("kind:", note.Kind(), "fields:", note.Len()) fmt.Println("keys:", note.Keys()) title, _ := note.Get("title") fmt.Println("title:", title.Str(), title.Kind()) tags, _ := note.Get("tags") fmt.Println("first tag:", tags.Index(0).Str(), "last tag:", tags.Index(tags.Len()-1).Str()) missing, ok := note.Get("due") fmt.Println("missing kind:", missing.Kind(), "present:", ok) }

go run ./cmd/l115

kind: object fields: 5
keys: [done id note tags title]
title: buy milk string
first tag: home last tag: errand
missing kind: null present: false

The keys are sorted, the first and last tag came from the array, and the missing field is a null value with a false. The null field that was set and the missing one print the same kind, which is why the ok boolean exists: a null value in a document is data, and a missing key is a different fact.

Why a sum type

The alternative is any: a number is a float64, an object a map[string]any and a null a nil. That is what encoding/json gives an untyped decode, and it costs a type assertion at every read and a nil that can mean two things. The Value type moves those checks into six methods and one kind, and the next lesson turns it back into text.

The cost is the size of the struct: a 64-byte value for every number. A program that parses millions of small values pays for it, which is why the benchmark at the end of the part compares this library with the standard one and reports both time and bytes.

Exercises

  1. Call Str on a number and Float on a string. Which zero do you get, and how would a program detect the mistake?
  2. Build an object with a nested array and print Len at both levels. Which two methods did you use?
  3. Store a document with a null field and one without it. What does Get return in each case, and how does a program tell them apart?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How is the kind of a Value stored?

    Answer

    In a ValueKind field that says which other field is valid

    Go has no sum type, so a discriminator does the job.

  2. What does ObjectValue do with the keys?

    Answer

    Sorts them so the encoding is stable

    Go map order is random.

  3. What does Float return for a string value?

    Answer

    Zero

    The accessors are total.

  4. What does Index return for an out-of-range index?

    Answer

    The null value

    A program checks Len first.

  5. What does Get return for a missing key?

    Answer

    Null and false

    The boolean separates missing from null.

  6. Why does Keys return a copy?

    Answer

    A caller must not reorder the internals

    The value stays immutable from outside.

  7. What is the cost of the design?

    Answer

    A large struct per value

    The benchmark reports it.

  8. What does ArrayValue keep?

    Answer

    The slice it is given

    The caller must not reuse it afterwards.

  9. How does a program tell a missing field from a JSON null?

    Answer

    By the ok from Get

    Both have NullKind.

  10. What does the untyped decode of encoding/json use?

    Answer

    any with map[string]any and float64

    It needs a type assertion at every read.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev