Decoder Token Walks JSON One Token At A Time

Inspect arbitrary JSON without a target struct by walking Decoder.Token one step at a time, and use Decoder.More to advance through arrays.

GoData Fetching

Code

snippet
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"strings"
)

func main() {
	payload := `{"service":"billing","replicas":3,"tags":["prod","eu"]}`

	decoder := json.NewDecoder(strings.NewReader(payload))
	depth := 0
	// Token 模式:不绑定目标结构,逐个消费 JSON 标记
	for {
		token, err := decoder.Token()
		if err == io.EOF {
			break
		}
		if err != nil {
			panic(err)
		}
		switch t := token.(type) {
		case json.Delim:
			// { [ 深度加一,} ] 减一,用于缩进展示层级
			if t == '{' || t == '[' {
				depth++
			} else {
				depth--
			}
			fmt.Printf("delim %c depth %d
", t, depth)
		default:
			fmt.Printf("%*s%v (%T)
", depth*2, "", token, token)
		}
	}

	// More():在数组内部逐元素推进
	arr := json.NewDecoder(strings.NewReader(`["a","b","c"]`))
	arr.Token() // 吃掉 [
	for arr.More() {
		token, _ := arr.Token()
		fmt.Println("element:", token)
	}
	arr.Token() // 吃掉 ]
}

Behavior in practice

Decoder Token Walks JSON One Token At A Time keeps everything in the function main.

Iteration happens inside for — everything outside it runs once. Every err != nil branch (1 site) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.

Points of care

  • Failures abort via panic(err) — nothing is returned for the caller to check, and nothing in the snippet recovers.

Putting it to use

The run prints element: — each prefix names the step that produced it.

Core lines

if err != nil {
	panic(err)
}

Interactive Tools for This Topic

FAQ

What happens when a call fails?
There are no error returns here: a non-nil `err` reaches `panic(err)` immediately.
What does Decoder Token Walks JSON One Token At A Time print when run?
The script runs standalone; its 1 labeled outputs include `element:`.