Flatten Nested JSON Maps Into Dot Paths

Unmarshal arbitrary JSON into map[string]any and flatten nested objects and arrays into dot-path keys with a recursive type-switch walk.

GoData Fetching

Code

gosnippet
51 lines
package main

import (
	"encoding/json"
	"fmt"
	"sort"
)

// flatten 把嵌套 JSON maps 递归压平成 dot paths 键
func flatten(prefix string, node map[string]any, out map[string]string) {
	for key, value := range node {
		path := key
		if prefix != "" {
			path = prefix + "." + key
		}
		switch v := value.(type) {
		case map[string]any:
			flatten(path, v, out) // 嵌套对象继续下钻
		case []any:
			for i, item := range v {
				if child, ok := item.(map[string]any); ok {
					flatten(fmt.Sprintf("%s.%d", path, i), child, out)
				} else {
					out[fmt.Sprintf("%s.%d", path, i)] = fmt.Sprint(item)
				}
			}
		default:
			out[path] = fmt.Sprint(value)
		}
	}
}

func main() {
	doc := `{"db":{"host":"localhost","port":5432},"features":["cache","tls"],"retries":3}`
	var tree map[string]any
	if err := json.Unmarshal([]byte(doc), &tree); err != nil {
		panic(err)
	}
	flat := make(map[string]string)
	flatten("", tree, flat)

	// map 遍历无序:排序后输出才稳定
	keys := make([]string, 0, len(flat))
	for k := range flat {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	for _, k := range keys {
		fmt.Printf("%s = %s\n", k, flat[k])
	}
}

How it works

Flatten Nested JSON Maps Into Dot Paths is built around the functions flatten and main.

Repetition is confined to for key, value := range node — the rest of the file is straight-line. Nothing continues past an unchecked error — 1 if err != nil branch, each ending in panic(err).

Watch out for

  • Adapting this to library code usually means replacing the panic(err) calls with error returns the caller can branch on.

Putting it to use

The signature carrying the work: func flatten(prefix string, node map[string]any, out map[string]string)

The demo flow inside main is flatten — run the file to see it end to end.

The core lines of the flow

for i, item := range v {
	if child, ok := item.(map[string]any); ok {
		flatten(fmt.Sprintf("%s.%d", path, i), child, out)
	} else {
		out[fmt.Sprintf("%s.%d", path, i)] = fmt.Sprint(item)
	}
}
for _, k := range keys {
	fmt.Printf("%s = %s\n", k, flat[k])
}
for k := range flat {
	keys = append(keys, k)
}

Interactive Tools for This Topic

FAQ

What is the error handling style?
The failure path is `panic(err)` — detected problems halt the run rather than being passed back.
How do you run Flatten Nested JSON Maps Into Dot Paths?
Execute it straight away — the program needs nothing beyond the runtime.