encoding/json/jsontext

Guided tour · Encoding · pkg.go.dev →

Low-level JSON tokenizer/emitter that underpins encoding/json/v2. Stream JSON without building a tree, with precise control over formatting.

Streaming decode

Decoder

dec := jsontext.NewDecoder(r)
for {
    tok, err := dec.ReadToken()
    if err == io.EOF { break }
    if err != nil { log.Fatal(err) }
    fmt.Println(tok.Kind(), tok.String())
}

Streaming encode

Encoder

enc := jsontext.NewEncoder(w)
enc.WriteToken(jsontext.BeginObject)
enc.WriteToken(jsontext.String("name"))
enc.WriteToken(jsontext.String("Ada"))
enc.WriteToken(jsontext.EndObject)