JSON 12 ๐ Modifying JSON Structures with JSON Patch (RFC 6902)
JSON Patch is the standard format for describing a sequence of operations that transform one JSON document into another. It is defined by RFC 6902, published in April 2013, and it is built directly on top of the JSON Pointer syntax from RFC 6901. A JSON Patch document is a JSON array of operation objects, and each operation has an op member that names the operation type and a path member that is a JSON Pointer to the target location. The array is applied sequentially, and the result is the transformed document. The format is the mechanism that lets a client send only the changes to a document instead of the entire document, and the HTTP PATCH method is the transport that carries it .
The six operations are add, remove, replace, move, copy, and test. Each one has a specific behaviour and a specific set of required members. The add inserts a value at the target location, the remove deletes the value at the target location, the replace replaces the value at the target location, the move removes the value from the from location and adds it to the path location, the copy deep-copies the value from the from location to the path location, and the test checks that the value at the target location equals the given value. The operations are the vocabulary, and the vocabulary is the mechanism that describes the document mutation.
Key point: A JSON Patch document is an array of operation objects, each with an op, a path, and the operation-specific members (value for add, replace, and test; from for move and copy). The add operation appends to an array when the path ends with -. The test operation is the validation mechanism: if it fails, the entire patch fails. The patch is atomic when used with the HTTP PATCH method: a failure in any operation means no changes are applied.
Why JSON Patch exists
The bandwidth problem. A document can be large, and the change can be small. Sending the entire document over the network to update a single field wastes the bandwidth and the processing time. The JSON Patch document is the diff, and the diff is the mechanism that sends only the changes. The server applies the patch to the current document, and the result is the new document. The bandwidth is the primary reason the format exists, and the HTTP PATCH method is the transport that makes it usable .
The concurrency problem. Two clients can edit the same document at the same time, and the second client’s update can overwrite the first client’s change. The test operation is the optimistic concurrency mechanism: the client includes a test operation that checks the current value, and if the value has changed, the patch fails and the client knows to re-fetch the document and retry. The test is the mechanism that makes the patch safe for the concurrent edits, and the failure is the signal that the client’s assumption about the document state was wrong.
The atomicity problem. A patch with the multiple operations can fail partway through, and the document can be left in the inconsistent state. The HTTP PATCH method is defined as atomic by RFC 5789: if any operation in the patch fails, the server must not apply any of the changes, and the document remains unchanged . The atomicity is the mechanism that keeps the document consistent, and the test operation is the mechanism that triggers the failure when the precondition is not met. The RFC 6902 states this explicitly: “Note that the HTTP PATCH method is atomic, as per [RFC5789]. Therefore, the following patch would result in no changes being made to the document at all (because the ‘test’ operation results in an error)” .
The operation problem. The six operations cover the common mutations: the add, the remove, the replace, the move, the copy, and the test. The operations are the vocabulary, and the vocabulary is the mechanism that describes the change without the custom logic. The move is the remove followed by the add, and the copy is the deep copy followed by the add. The two are the convenience operations that the format provides, and the underlying behaviour is defined in terms of the primitive operations.
The safety problem. The JSON Patch document can be used to modify the arbitrary parts of the document, and the malicious patch can be used to corrupt the data or to escalate the privileges. The path and the from are the JSON Pointers, and the pointer evaluation is the mechanism that resolves the location. The implementations must validate the path and the operation, and the RFC 6902 notes the CSRF consideration: a JSON Patch document containing the sensitive information could be exposed to the attackers through the older browsers that load the arbitrary JSON arrays . The security is the application’s responsibility, and the test operation is the mechanism that adds the precondition check.
a. The operation types and their behaviour
The add operation inserts a value at the target location. The behaviour depends on what the target location references. If the target is the root of the document, the value becomes the entire document. If the target is an object member that does not exist, the member is added. If the target is an object member that exists, the member’s value is replaced. If the target is an array index, the value is inserted at the index, and the elements at or above the index are shifted to the right. The index must not be greater than the number of the elements in the array. The - character as the index appends the value to the array .
// The add operation
{ "op": "add", "path": "/a/b/c", "value": [ "foo", "bar" ] }
The target location must reference the root, an object member to add to, or an array element to add to. The target location itself often does not exist, and the add operation is defined to ignore the pointer’s error handling and add the value. However, the object or the array that contains the target must exist, or the operation fails. The add with the target /a/b on the document { "a": { "foo": 1 } } is not an error, because the a exists and the b will be added to its value. The same operation on the document { "q": { "bar": 2 } } is an error, because the a does not exist .
The remove operation deletes the value at the target location. The target location must exist, or the operation fails. The remove is the mechanism that deletes the object member or the array element, and the array element is removed and the subsequent elements are shifted to the left.
// The remove operation
{ "op": "remove", "path": "/a/b/c" }
The replace operation replaces the value at the target location with the new value. The target location must exist, or the operation fails. The replace is the equivalent of the remove followed by the add, and it is the mechanism that changes the value without changing the structure.
// The replace operation
{ "op": "replace", "path": "/a/b/c", "value": 42 }
The move operation removes the value at the from location and adds it to the path location. The from location must exist, or the operation fails. The from location must not be a proper prefix of the path location, which means a location cannot be moved into one of its children . The move is the mechanism that relocates the value, and the two-step behaviour is the mechanism that defines the result.
// The move operation
{ "op": "move", "from": "/a/b/c", "path": "/a/b/d" }
The copy operation deep-copies the value at the from location and adds it to the path location. The from location must exist, or the operation fails. The copy is the mechanism that duplicates the value, and the deep copy is the mechanism that ensures the copy is independent of the original.
// The copy operation
{ "op": "copy", "from": "/a/b/c", "path": "/a/b/d" }
The test operation checks that the value at the target location equals the given value. The target location must exist, and the value must be equal, or the operation fails. The test is the validation mechanism, and the failure is the signal that the document is not in the expected state. The RFC 6902 states that the test operation is the mechanism that makes the patch conditional, and the HTTP PATCH atomicity means that the failed test aborts the entire patch .
// The test operation
{ "op": "test", "path": "/a/b/c", "value": "foo" }
b. The atomicity, the error handling, and the libraries
The JSON Patch document is applied sequentially, and the operations are evaluated in the order they appear in the array. If an operation fails, the evaluation terminates, and the entire patch is not successful. The RFC 6902 states that the evaluation “SHOULD terminate and application of the entire patch document SHALL NOT be deemed successful” . The HTTP PATCH method adds the atomicity requirement: the server must not apply any of the changes if the patch fails, and the document remains in the original state .
The error handling is the mechanism that keeps the document consistent. The implementation must validate the op member, the path member, and the operation-specific members. The add must have the value, the replace must have the value, the move must have the from, the copy must have the from, and the test must have the value. The missing member is the error, and the invalid pointer is the error. The RFC 6902 defines the error handling behaviour for each operation, and the implementation must follow it.
The libraries implement the RFC 6902 in the different languages. The rfc6902 npm package provides the applyPatch and the createPatch functions. The applyPatch(object, patch) applies the operations in place and returns the array of the results: the null for the successful operation and the Error instance for the failed one. The createPatch(input, output) generates the patch that transforms the input into the output, and the diff is the Levenshtein-type implementation with the remove, the add, and the replace operations . The .NET Microsoft.AspNetCore.JsonPatch provides the JsonPatchDocument<TModel> with the ApplyTo method, and the operations are the Add, the Remove, the Replace, the Move, the Copy, and the Test . The Dart PatchOperation class provides the factory constructors for each operation, and the fromJson factory parses the RFC 6902 wire format . The Kubernetes patchesJson6902 uses the same format for the resource patches, and the YAML form is the human-readable alternative to the JSON array .
// The rfc6902 applyPatch
import { applyPatch } from "rfc6902";
const document = { foo: "bar" };
const patch = [
{ op: "add", path: "/baz", value: "qux" },
{ op: "replace", path: "/foo", value: "baz" },
];
const results = applyPatch(document, patch);
// The document is modified in place.
// The results is [null, null] for the successful operations.
The applyPatch modifies the document in place, and the results array is the mechanism that reports the success or the failure per operation. The createPatch is the reverse: it computes the patch from the two documents, and the patch is the mechanism that stores the difference.
Complete Example Session
// ============================================
// PART 1: THE TARGET DOCUMENT
// ============================================
const target = {
foo: "bar",
numbers: [1, 2, 3],
nested: { a: 1 },
};
// The target is the document to be patched.
// ============================================
// PART 2: THE ADD OPERATION
// ============================================
const addPatch = [
{ op: "add", path: "/baz", value: "qux" },
{ op: "add", path: "/numbers/-", value: 4 },
];
// The first add adds the baz member.
// The second add appends 4 to the numbers array.
// ============================================
// PART 3: THE REMOVE OPERATION
// ============================================
const removePatch = [
{ op: "remove", path: "/foo" },
];
// The remove deletes the foo member.
// ============================================
// PART 4: THE REPLACE OPERATION
// ============================================
const replacePatch = [
{ op: "replace", path: "/nested/a", value: 2 },
];
// The replace changes the nested.a value to 2.
// ============================================
// PART 5: THE MOVE OPERATION
// ============================================
const movePatch = [
{ op: "move", from: "/nested/a", path: "/nested/b" },
];
// The move relocates the nested.a to the nested.b.
// The nested.a is removed and the nested.b is added.
// ============================================
// PART 6: THE COPY OPERATION
// ============================================
const copyPatch = [
{ op: "copy", from: "/nested/a", path: "/nested/c" },
];
// The copy duplicates the nested.a to the nested.c.
// The nested.a remains in place.
// ============================================
// PART 7: THE TEST OPERATION
// ============================================
const testPatch = [
{ op: "test", path: "/foo", value: "bar" },
{ op: "replace", path: "/foo", value: "baz" },
];
// The test checks that the foo is "bar".
// If the test passes, the replace changes the foo to "baz".
// If the test fails, the entire patch fails.
// ============================================
// PART 8: THE ATOMICITY
// ============================================
const failingPatch = [
{ op: "test", path: "/foo", value: "wrong" },
{ op: "replace", path: "/foo", value: "baz" },
];
// The test fails because the foo is "bar", not "wrong".
// The replace is not applied.
// The entire patch fails and the document is unchanged.
// ============================================
// PART 9: THE LIBRARY
// ============================================
import { applyPatch } from "rfc6902";
const results = applyPatch(target, failingPatch);
// The results contain an Error for the failed test.
// The target is not modified by the failed patch.
// ============================================
// PART 10: THE CHECKLIST
// ============================================
// [ ] The patch is an array of the operation objects.
// [ ] The add has the value.
// [ ] The remove has the path.
// [ ] The replace has the value.
// [ ] The move has the from.
// [ ] The copy has the from.
// [ ] The test has the value.
// [ ] The patch is atomic with the HTTP PATCH.
The ten parts covered the target document, the add operation, the remove operation, the replace operation, the move operation, the copy operation, the test operation, the atomicity, the library, and the checklist. The through-line is that the operations are the vocabulary, and the test is the precondition.
Quick Reference
The six operations
| Operation | Required members | Behaviour |
|---|---|---|
add | path, value | Insert or replace the value |
remove | path | Delete the value |
replace | path, value | Replace the value |
move | from, path | Remove from from, add to path |
copy | from, path | Deep copy from from to path |
test | path, value | Check the value equality |
The add behaviour
| Target | Behaviour |
|---|---|
| The root | The value becomes the document |
| The object member (missing) | The member is added |
| The object member (existing) | The value is replaced |
| The array index | The value is inserted, the elements shift |
The - index | The value is appended |
The move and copy constraints
| Constraint | Rule |
|---|---|
The from | Must exist |
| The move prefix | The from must not be a prefix of the path |
| The copy | The deep copy is independent |
The libraries
| Language | Package | Notes |
|---|---|---|
| JavaScript | rfc6902 | The applyPatch and the createPatch |
| .NET | Microsoft.AspNetCore.JsonPatch | The JsonPatchDocument<T> |
| Dart | PatchOperation | The factory constructors |
| Kubernetes | patchesJson6902 | The YAML or the JSON form |
Best Practices
โ Do This:
// Use the test for the precondition
{ op: "test", path: "/foo", value: "bar" } // โ
// Use the - for the array append
{ op: "add", path: "/numbers/-", value: 4 } // โ
// Use the atomic HTTP PATCH
// The failed operation aborts the entire patch. // โ
โ Don’t Do This:
// Move a location into its child
{ op: "move", from: "/a", path: "/a/b" } // the prefix error // โ
// Omit the value on the add
{ op: "add", path: "/baz" } // the missing member // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| The patch applies partially | The non-atomic implementation | Use the HTTP PATCH or the transactional apply |
| The add fails | The parent object does not exist | Ensure the parent exists |
| The move fails | The from does not exist | Check the source path |
| The test fails | The document state changed | Re-fetch the document and retry |
Real-World Examples
1. The add
{ "op": "add", "path": "/baz", "value": "qux" }
2. The remove
{ "op": "remove", "path": "/foo" }
3. The replace
{ "op": "replace", "path": "/foo", "value": "baz" }
4. The move
{ "op": "move", "from": "/a/b", "path": "/a/c" }
5. The copy
{ "op": "copy", "from": "/a/b", "path": "/a/c" }
6. The test
{ "op": "test", "path": "/foo", "value": "bar" }
7. The append
{ "op": "add", "path": "/items/-", "value": "new" }
8. The nested path
{ "op": "replace", "path": "/a/b/c", "value": 42 }
9. The atomic patch
const results = applyPatch(document, patch);
10. The generate patch
const patch = createPatch(input, output);
Visual
The Patch Application
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE PATCH APPLICATION โ
โ โ
โ The target document โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ The operation 1 โ The add โ
โ โโโโโโโโโโโโฌโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ The operation 2 โ The replace โ
โ โโโโโโโโโโโโฌโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ The operation 3 โ The test โ
โ โ โ If it fails, the patch aborts โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Atomicity
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE ATOMICITY โ
โ โ
โ The patch: โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ test: foo = "bar" โ The precondition โ
โ โ replace: foo = "baz"โ The change โ
โ โโโโโโโโโโโโฌโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ The test fails โ The foo is not "bar" โ
โ โโโโโโโโโโโโฌโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ No changes applied โ The document is unchanged โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Add Behaviour
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE ADD BEHAVIOUR โ
โ โ
โ The target is the object member: โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ The member exists โ The value is replaced โ
โ โ The member missing โ The member is added โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ
โ The target is the array index: โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ The index is a digitโ The value is inserted โ
โ โ The index is - โ The value is appended โ
โ โโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| The format | The array of the operation objects |
| The operations | add, remove, replace, move, copy, test |
| The required members | path, value (the add, the replace, the test), from (the move, the copy) |
| The append | The - index in the add |
| The atomicity | The HTTP PATCH is atomic |
| The test | The precondition check, the failure aborts the patch |
| The media type | application/json-patch+json |
Key takeaways:
- The JSON Patch document is an array of operation objects. Each operation has an
opand apath, and the operation-specific members. The array is applied sequentially, and the result is the transformed document . - The
addoperation appends to an array with the-index. The-is the special JSON Pointer token that means the position after the last element, and theaddwith the-appends the value. Theaddon the object member replaces the existing value or adds the new member . - The
testoperation is the precondition check. It verifies the current value, and the failure aborts the entire patch. Thetestis the optimistic concurrency mechanism, and the atomicity is the reason the failed test leaves the document unchanged . - The HTTP PATCH is atomic. The RFC 5789 defines the atomicity: if any operation fails, no changes are applied. The RFC 6902 states this explicitly, and the atomicity is the mechanism that keeps the document consistent .
- The
moveand thecopyare the convenience operations. Themoveis the remove followed by the add, and thecopyis the deep copy followed by the add. Thefromlocation must exist, and thefrommust not be a prefix of thepathfor the move .
Remember: The JSON Patch is the standard for the JSON document mutation. It is the array of operations, the JSON Pointer paths, the test precondition, and the atomicity of the HTTP PATCH. The add appends with the -, the test aborts on the failure, and the move and the copy are the relocations and the duplications. The format is the vocabulary, and the atomicity is the guarantee.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!