Deep Merge Configuration Maps
Merge layered JSON-like configuration maps recursively so nested objects combine while scalar overrides replace base values.
Code
package main
import (
"encoding/json"
"fmt"
)
func Merge(dst, src map[string]any) map[string]any {
if dst == nil {
dst = make(map[string]any)
}
for key, value := range src {
if incoming, ok := value.(map[string]any); ok {
if existing, ok := dst[key].(map[string]any); ok {
dst[key] = Merge(existing, incoming)
continue
}
dst[key] = Merge(nil, incoming)
continue
}
dst[key] = value
}
return dst
}
func main() {
base := map[string]any{
"server": map[string]any{"port": 8080.0, "tls": false},
"name": "api",
}
override := map[string]any{
"server": map[string]any{"port": 9090.0},
"debug": true,
}
merged := Merge(base, override)
encoded, _ := json.Marshal(merged)
fmt.Println(string(encoded))
}
How it works
Everything happens inside the functions Merge and main.
Repetition is confined to for key, value := range src — the rest of the file is straight-line.
What to watch for
- The environment needs no preparation beyond having the interpreter or compiler.
Applying it
The main signature reads func Merge(dst, src map[string]any) map[string]any
Execute the file and main walks through Merge, in that order.
Statements that matter
for key, value := range src {
if incoming, ok := value.(map[string]any); ok {
if existing, ok := dst[key].(map[string]any); ok {
dst[key] = Merge(existing, incoming)
continue
}
dst[key] = Merge(nil, incoming)
continue
}
dst[key] = value
}
dst = make(map[string]any)
Interactive Tools for This Topic
INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.TOML to JSON ConverterParse TOML configuration into JSON, supporting tables, arrays of tables, inline tables, and basic or literal strings.
FAQ
- How do you run Deep Merge Configuration Maps?
- The runtime alone is enough: execute the file as a complete program.
Report a problem with this exampleOpens a pre-filled issue on GitHub.