# How to apply a JSON Patch to a document in Go

> Apply RFC 6902 operations to a stored JSON document in a Go service with evanphx/json-patch, so a failed test op leaves the stored bytes exactly as they were.

Source: https://voxgig.com/howto/apply-a-json-patch-in-go

- Audience: api-producer
- Level: intermediate
- Languages: go
- Verified: 2026-11-29
- Published: 2026-11-29

## Short answer

Decode the client's operations with `jsonpatch.DecodePatch` from evanphx/json-patch, apply them to the stored bytes with `ApplyWithOptions`, and replace the stored document only when that call returns no error. Patch the bytes, never a struct decoded from them. Turn off negative indexes, cap copy growth, and answer 409 for a failed test op or a missing path.

---
## You will need

Go 1.24 or later and a handler that reads the request body. Verified 2026-11-29 against Go 1.24.7
and Go 1.25.14 with evanphx/json-patch v5.9.11. The operations and their error rule come from
[RFC 6902](https://www.rfc-editor.org/rfc/rfc6902.html), the paths inside them from
[RFC 6901](https://www.rfc-editor.org/rfc/rfc6901.html), and the status codes from
[RFC 5789 section 2.2](https://www.rfc-editor.org/rfc/rfc5789.html#section-2.2).

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [evanphx/json-patch](https://pkg.go.dev/github.com/evanphx/json-patch/v5) | Clients send RFC 6902 operations and you store JSON as bytes | Works on `[]byte`, accepts negative indexes by default, and compares numbers in `test` by their spelling | Clients only ever replace whole members, so merge patch is enough |
| [Hand-rolled JSON Pointer walk over map[string]any](https://www.rfc-editor.org/rfc/rfc6901.html#section-4) | You cannot add a dependency and the documents are small | About 270 lines to own, re-sorted keys, and integers past 2^53 rounded on every write | Documents carry large ids or key order matters to a reader |
| [JSON Merge Patch](https://www.rfc-editor.org/rfc/rfc7396.html) | Clients send a partial document and never edit inside arrays | Cannot change one array element, cannot set a member to null, and has no test op | Clients need a conditional edit or an array edit |

evanphx/json-patch handles pointer escapes, the `-` index and all six operations, at the price of
two defaults that a public endpoint should override. A hand-rolled walk compares numbers by value because everything
decodes to `float64`, and it pays for that with lost precision and lost key order. Merge patch is
the simplest for a client to write, but its null means delete.

## Apply the patch to the stored bytes

`ApplyWithOptions` returns a patched copy, and in the tests here it left the stored slice untouched
when an operation failed. Hold one lock across the version check, the apply and the swap, and
store the result only after the call succeeds.

```go title="patchstore/store.go"
func options() *jsonpatch.ApplyOptions {
	o := jsonpatch.NewApplyOptions()
	o.SupportNegativeIndices = false // RFC 6901 has no negative index
	o.AccumulatedCopySizeLimit = MaxCopyGrowth
	o.EscapeHTML = false
	return o
}

// update runs fn on the stored bytes and keeps its result only when fn
// returns no error. The lock covers the version check, fn and the swap.
// An empty ifMatch, or "*", skips the version check.
func (s *Store) update(id, ifMatch string, fn func([]byte) ([]byte, error)) ([]byte, string, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	e, ok := s.docs[id]
	if !ok {
		return nil, "", ErrNotFound
	}
	if ifMatch != "" && ifMatch != "*" && ifMatch != etag(e.version) {
		return nil, "", ErrStale
	}
	next, err := fn(e.body)
	if err != nil {
		return nil, "", err
	}
	s.docs[id] = entry{body: next, version: e.version + 1}
	return append([]byte(nil), next...), etag(e.version + 1), nil
}

// ApplyJSONPatch applies an RFC 6902 patch to the stored bytes.
func (s *Store) ApplyJSONPatch(id, ifMatch string, patchJSON []byte) ([]byte, string, error) {
	canon, err := CanonicalNumbers(patchJSON)
	if err != nil {
		return nil, "", fmt.Errorf("%w: %w", ErrBadPatch, err)
	}
	patch, err := jsonpatch.DecodePatch(canon)
	if err != nil {
		return nil, "", fmt.Errorf("%w: %w", ErrBadPatch, err)
	}
	return s.update(id, ifMatch, func(doc []byte) ([]byte, error) {
		next, err := patch.ApplyWithOptions(doc, options())
		if err != nil {
			return nil, fmt.Errorf("%w: %w", ErrConflict, err)
		}
		return next, nil
```

The library's `NewApplyOptions` sets `SupportNegativeIndices` to true, so `/tags/-1` removes the
last tag, a reading the RFC 6901 grammar does not allow. `AccumulatedCopySizeLimit` defaults to
zero, which means no limit, so one patch of repeated `copy` operations can grow a document without
bound. `CanonicalNumbers` is the sample's own function, and the section on failures explains why it is there.

## Map the errors to status codes

RFC 5789 suggests 400 for a malformed patch, 409 when the patch cannot apply to the resource's
state, and 415 with an `Accept-Patch` header for a format the server does not take. An `If-Match`
that names a superseded version gets 412, which RFC 5789 calls the most helpful answer to a failed
precondition and [RFC 9110 section 13.1.1](https://www.rfc-editor.org/rfc/rfc9110.html#section-13.1.1) allows.
The handler reads the body through
[`http.MaxBytesReader`](https://pkg.go.dev/net/http#MaxBytesReader) and switches on the wrapped
error.

```go title="patchstore/handler.go"
		doc, tag, err := apply(r.PathValue("id"), r.Header.Get("If-Match"), body)
		switch {
		case errors.Is(err, ErrNotFound):
			http.Error(w, err.Error(), http.StatusNotFound)
		case errors.Is(err, ErrBadPatch):
			http.Error(w, err.Error(), http.StatusBadRequest)
		case errors.Is(err, ErrConflict):
			http.Error(w, err.Error(), http.StatusConflict)
		case errors.Is(err, ErrStale):
			http.Error(w, err.Error(), http.StatusPreconditionFailed)
		case err != nil:
			http.Error(w, "internal error", http.StatusInternalServerError)
		default:
			w.Header().Set("Content-Type", "application/json")
			w.Header().Set("ETag", tag)
			w.Write(doc)
		}
```

The demo stores one document, serves the handler on a loopback port, and sends five patches. The
second replaces the title and then tests a value that no longer holds.

```bash
go run .
```

```text output
1. test, then replace, append and remove
  200 ETag "v2" {"id":"svc-42","title":"Checkout","tags":["api","ga"],"limits":{"rps":100},"labels":{"team/owner":"checkout"},"x-audit":{"by":"ops"}}
2. replace the title, then a test that fails
  409 patch does not apply: testing value /limits/rps failed: test failed
  stored document unchanged: true
3. a merge patch
  200 ETag "v3" {"id":"svc-42","title":"Checkout v2","tags":["api","ga"],"limits":{"rps":100},"labels":{"team/owner":"checkout"}}
4. a patch in a format the handler does not accept
  415 unsupported patch format
5. a patch sent with If-Match naming the first version
  412 document has changed since that version
```

The first patch reached `team/owner` through the pointer `/labels/team~1owner` and appended with
`/tags/-`. The title replace in the second patch ran before the failed test, but the swap never
happened, so the stored document still says `Checkout` and keeps the `ETag` value `"v2"`. The merge patch
deleted `x-audit` by sending it as null. The fifth patch named version one and was refused whole.

## Compare the three on one document

The same two edits, through the library, the hand-rolled walk in `handrolled/apply.go`, and a merge
patch through the library's `MergePatch`.

```bash
go run ./cmd/compare
```

```text output
stored      {"title":"Checkout","tags":["api","beta"],"owner":"ops","seq":9007199254740993}

edit: replace the second tag
  library   {"title":"Checkout","tags":["api","ga"],"owner":"ops","seq":9007199254740993}
  by hand   {"owner":"ops","seq":9007199254740992,"tags":["api","ga"],"title":"Checkout"}
  merge     {"title":"Checkout","tags":["api","ga"],"owner":"ops","seq":9007199254740993}

edit: set owner to null
  library   {"title":"Checkout","tags":["api","beta"],"owner":null,"seq":9007199254740993}
  by hand   {"owner":null,"seq":9007199254740992,"tags":["api","beta"],"title":"Checkout"}
  merge     {"title":"Checkout","tags":["api","beta"],"seq":9007199254740993}
```

The hand-rolled walk sorted the keys and changed `seq`, because
[`encoding/json`](https://pkg.go.dev/encoding/json#Unmarshal) decodes a number into `float64`
when the target is `any`. The merge patch had to send the whole `tags` array to change one element,
and it removed `owner` where the other two set it to null, as
[RFC 7396 section 2](https://www.rfc-editor.org/rfc/rfc7396.html#section-2) specifies.[^1]

## Check it worked

The tests apply a patch whose test op fails after two operations that succeed, and compare the
stored bytes before and after. Others check the escapes, the refused negative index, the copy
cap, a stale `If-Match`, each status code, and 50 concurrent appends.

```bash
go test -count=1 -v ./... | grep -E '^(=== RUN|--- FAIL|FAIL)'
```

```text output
=== RUN   TestPatchingTheBytesKeepsAFieldTheStructLacks
=== RUN   TestPatchingADecodedStructDropsTheField
=== RUN   TestAgreesWithTheLibrary
=== RUN   TestRefusesWhatTheRFCRefuses
=== RUN   TestComparesNumbersByValue
=== RUN   TestLosesKeyOrderAndIntegersAbove2To53
=== RUN   TestAFailedTestOpLeavesTheStoredDocumentUnchanged
=== RUN   TestAPassingTestOpLetsThePatchApply
=== RUN   TestPointerEscapesAndTheDashIndex
=== RUN   TestANegativeIndexIsRefused
=== RUN   TestCopyGrowthIsCapped
=== RUN   TestNumbersCompareByValueOnlyAfterCanonicalization
=== RUN   TestCanonicalNumbersKeepsOrderStringsAndBigIntegers
=== RUN   TestAMergePatchNullDeletesTheMember
=== RUN   TestConcurrentPatchesAllLand
=== RUN   TestHandlerStatusCodes
=== RUN   TestIfMatchRefusesAStaleVersion
=== RUN   TestAddNeedsTheParentToExist
```

No `FAIL` line appears. `TestAgreesWithTheLibrary` holds the hand-rolled walk to the library's
result on ten patches, including `~01`, which RFC 6901 decodes to `~1` and never to `/`.[^2]

## When it goes wrong

A field disappears after an unrelated patch. The handler decoded the stored document into its
read struct, marshaled the struct, and patched that, so every member the struct lacks was gone
before the patch ran.

```bash
go run ./cmd/pitfall
```

```text output
patched the stored bytes:  {"id":"svc-42","title":"Checkout v2","limits":{"rps":50},"x-audit":{"by":"ops"}}
patched a decoded struct:  {"id":"svc-42","title":"Checkout v2","limits":{"rps":50}}
```

Patch the stored bytes, as `viaBytes` in `cmd/pitfall/main.go` does, and keep the struct for reads.

A test op fails on a value that matches. RFC 6902 section 4.6 compares numbers by value, but the
library compares the bytes, so a stored `1.50` fails a test for `1.5`. The sample rewrites every
number in the stored document and in each patch to one spelling before applying. It works on the
decimal digits rather than through `float64`, so a 20-digit id keeps its value.

```bash
go run ./cmd/numbers
```

```text output
library, bytes as sent:     error: testing value /price failed: test failed
library, numbers rewritten: {"sku":"A-1","price":1.75}
by hand:                    {"price":1.75,"sku":"A-1"}
```

A 409 with `missing value` names a parent that does not exist. RFC 6902 requires the parent of an
`add` target to exist, so `/limits/burst/max` fails when `burst` is absent. The library's
`EnsurePathExistsOnAdd` option creates the parents, a departure from the RFC to turn on only when
your clients expect it.

## When not to do this

Do not accept JSON Patch when every client edit replaces whole members. Merge patch is a partial
document that any client can build, and the library applies it with one call.

Do not keep the defaults of `NewApplyOptions` for patches from outside your service. Negative
indexes and unlimited copy growth are both on until you turn them off.

Do not rely on the mutex in this sample once more than one process writes, because it orders
patches inside one process only. With several instances, the version check in `update` has to
happen inside the shared store's own write to give the same guarantee.

Do not hand-roll the walk to avoid a dependency unless you also own a test that compares it with a
reference implementation, as `TestAgreesWithTheLibrary` does.

## Related how-tos

- [Read a value at a nested path without null checks](/howto/read-a-nested-value-by-path)

- [Merge nested config objects with predictable precedence](/howto/merge-nested-config-objects-with-precedence)

- [Return validation errors a client can map to a form](/howto/field-level-validation-errors-clients-can-map)

- [Validate a webhook payload's shape before handling it](/howto/validate-webhook-payload-shape-before-processing)

## Last verified

Verified 2026-11-29 against Go 1.24.7 and Go 1.25.14 with evanphx/json-patch v5.9.11. Every
output block is what the command preceding it printed. All three approaches ran.

[^1]: JSON Merge Patch was published twice in one month. [RFC 7386](https://www.rfc-editor.org/rfc/rfc7386.html)
and [RFC 7396](https://www.rfc-editor.org/rfc/rfc7396.html) both carry October 2014 in their
headers, with the same two authors and the same title, and the header of the second says it
obsoletes the first. With leading spaces removed, the two texts differ only in those headers. The
algorithm is set out as indented steps with no braces, so the spaces matter. The first edition
puts the line that empties a non-object target level with the `if` meant to guard it.

[^2]: [RFC 6901 section 4](https://www.rfc-editor.org/rfc/rfc6901.html#section-4) spends a whole
sentence on the order of two string replacements: `~1` becomes `/` first, then `~0` becomes `~`.
Done the other way round, `~01` turns into `/`. The same section defines `-` as the member after
the last array element, observes that it can therefore never resolve, and leaves its meaning to
whichever specification uses pointers. RFC 6902 gave it one in its description of `add`, where
the dash appends.