Master JSON Patch in Go: A Practical Guide to Efficient JSON Modifications
This article introduces the Go json-patch library, explains its RFC 6902‑based operations, provides step‑by‑step code examples, details each operation, and offers advanced usage tips and best practices for applying JSON patches in backend applications.
Introduction
json-patch is a Go library that implements the JSON Patch standard (RFC 6902), allowing partial updates of JSON documents without rewriting the entire document.
Features and Characteristics
Supported operations : add, remove, replace, move, copy, test.
Easy integration : can be added to existing Go projects, especially where JSON data is frequently modified.
Performance : optimized for common operations, remains efficient on large JSON payloads.
Basic Usage
The following example demonstrates how to apply a JSON Patch to a document using the json-patch library.
package main
import (
"fmt"
jsonpatch "github.com/evanphx/json-patch"
)
func main() {
// Original JSON document
original := []byte(`{
"name": "John",
"age": 30,
"city": "New York"
}`)
// JSON Patch document
patch := []byte(`[
{ "op": "replace", "path": "/name", "value": "Jane" },
{ "op": "remove", "path": "/age" },
{ "op": "add", "path": "/country", "value": "USA" }
]`)
// Create patch object
patchObj, err := jsonpatch.DecodePatch(patch)
if err != nil {
panic(err)
}
// Apply patch
patched, err := patchObj.Apply(original)
if err != nil {
panic(err)
}
fmt.Printf("Patched document: %s
", patched)
}Detailed Operation Descriptions
add : adds a new key‑value pair at the specified path; overwrites if the path already exists.
remove : deletes the key‑value pair at the given path.
replace : replaces the value at the path; similar to add but the path must already exist.
move : moves a value from one path to another.
copy : copies a value from one path to another.
test : checks whether the value at a path matches the expected value, useful for conditional patches.
for _, op := range p {
switch op.Kind() {
case "add":
err = p.add(&pd, op)
case "remove":
err = p.remove(&pd, op)
case "replace":
err = p.replace(&pd, op)
case "move":
err = p.move(&pd, op)
case "test":
err = p.test(&pd, op)
case "copy":
err = p.copy(&pd, op, &accumulatedCopySize)
default:
err = fmt.Errorf("Unexpected kind: %s", op.Kind())
}
}Advanced Usage
Conditional application : combine the test operation to apply subsequent operations only when a condition is met.
Batch processing : group multiple operations into a single patch set and apply them in one step.
Typical Use Cases
API request/response modification in RESTful services.
Dynamic configuration file updates.
Data synchronization across distributed nodes.
Best Practices
Backup original JSON before applying patches.
Validate patches with the test operation to ensure safety.
Handle errors from MergePatch or Apply to maintain system stability.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Ops Development & AI Practice
DevSecOps engineer sharing experiences and insights on AI, Web3, and Claude code development. Aims to help solve technical challenges, improve development efficiency, and grow through community interaction. Feel free to comment and discuss.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
