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.
Code
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
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.