JSON Decodes Into Any Value Trees

Unmarshal into any and type-switch on map[string]any, []any, float64, and string branches to inspect JSON whose structure is only known at runtime.

GoData Integrity

Code

gosnippet
47 lines
package main

import (
	"encoding/json"
	"fmt"
)

// countShapes walks the decoded tree and counts what it finds.
func countShapes(v any) (objects, arrays, numbers, strings int) {
	switch t := v.(type) {
	case map[string]any:
		objects++
		for _, child := range t {
			o, a, n, s := countShapes(child)
			objects, arrays, numbers, strings = objects+o, arrays+a, numbers+n, strings+s
		}
	case []any:
		arrays++
		for _, child := range t {
			o, a, n, s := countShapes(child)
			objects, arrays, numbers, strings = objects+o, arrays+a, numbers+n, strings+s
		}
	case float64:
		numbers++
	case string:
		strings++
	}
	return objects, arrays, numbers, strings
}

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

	// Unmarshal into any: objects decode to map[string]any, numbers to float64
	var tree map[string]any
	if err := json.Unmarshal([]byte(payload), &tree); err != nil {
		panic(err)
	}
	fmt.Printf("%T with %d keys\n", tree, len(tree))

	objs, arrs, nums, strs := countShapes(tree)
	fmt.Printf("objects=%d arrays=%d numbers=%d strings=%d\n", objs, arrs, nums, strs)

	// type assertion reaches into one branch of the tree
	replicas, ok := tree["replicas"].(float64)
	fmt.Println("replicas:", replicas, "present:", ok)
}

Inside this example — JSON Decodes Into Any Value Trees

The snippet is organized around the functions countShapes and main.

A single loop drives the file — for _, child := range t. Every err != nil branch (1 site) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.

Watch out for

  • Zero packages pulled in — the runtime ships every API this code touches.
  • Failures abort via panic(err) — nothing is returned for the caller to check, and nothing in the snippet recovers.

Putting it to use

Entry signature: func countShapes(v any) (objects, arrays, numbers, strings int)

The file’s steps show up in the output as objects=, replicas:.

main sequences countShapes; executing the file runs that flow once.

Core lines

for _, child := range t {
	o, a, n, s := countShapes(child)
	objects, arrays, numbers, strings = objects+o, arrays+a, numbers+n, strings+s
}

Interactive Tools for This Topic

FAQ

How should callers handle failures?
By terminating the run: `panic(err)` fires at each of the 1 check, so callers see failures only as a stopped program.
What does JSON Decodes Into Any Value Trees print when run?
Invoke the file as-is — the `objects=`, `replicas:` prefixes identify which step printed each line.