JSON Merge Patch Overlay Apply
Decode an RFC 7386 style patch into a map and overlay it on a base document, keeping nested objects merged and null values removed.
Code
package main
import (
"encoding/json"
"fmt"
)
// RFC 7386 语义:对象递归合并,null 表示删除字段,其他类型整体覆盖
func applyPatch(dst, patch map[string]any) map[string]any {
for key, value := range patch {
if value == nil {
delete(dst, key) // null = 删除
continue
}
patchObj, isObj := value.(map[string]any)
dstObj, wasObj := dst[key].(map[string]any)
if isObj && wasObj {
dst[key] = applyPatch(dstObj, patchObj)
continue
}
dst[key] = value // 标量/数组整体替换
}
return dst
}
func main() {
base := []byte("{"name":"api","retry":{"attempts":3,"backoff":"1s"},"debug":true}")
patch := []byte("{"retry":{"attempts":5},"debug":null,"owner":"infra"}")
var dst, overlay map[string]any
if err := json.Unmarshal(base, &dst); err != nil {
fmt.Println("base:", err)
return
}
if err := json.Unmarshal(patch, &overlay); err != nil {
fmt.Println("patch:", err)
return
}
merged, _ := json.Marshal(applyPatch(dst, overlay))
fmt.Println(string(merged))
}How it works
JSON Merge Patch Overlay Apply comes down to the functions applyPatch and main.
A single loop drives the file — for key, value := range patch. Error handling is inline: 2 places test err != nil and branch immediately.
What to watch for
- No external packages — everything relies on the language’s built-in APIs.
Using it
Signature: func applyPatch(dst, patch map[string]any) map[string]any
Running the file prints labeled results such as base:, patch: — each operation’s effect is visible in the output.
Running the file executes main, which drives applyPatch in order.
Key statements
base := []byte("{"name":"api","retry":{"attempts":3,"backoff":"1s"},"debug":true}")
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
- What does JSON Merge Patch Overlay Apply print when run?
- Execute the whole file; each printed line is prefixed with a label like `base:`, `patch:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.