JSON Patch: Represent JSON document changes as operations
JSON Patch describes changes to a JSON document as an ordered array of operations. It is commonly sent as the body of an HTTP PATCH request with media type application/json-patch+json. Each operation states what to do at a path; this is not the same as merging an object containing selected fields.
JSON Patch describes changes to a JSON document as an ordered array of operations. It is commonly sent as the body of an HTTP PATCH request with media type application/json-patch+json. Each operation states what to do at a path; this is not the same as merging an object containing selected fields.
Operations run in order
RFC 6902 defines add, remove, replace, move, copy, and test. Each uses a JSON Pointer path, and each operation sees the result of the previous one. A test checks that a current value matches an expected value; if it fails, the patch fails. Under PATCH atomicity, the server must not save a partial result when an operation fails.
add inserts a member or array element. Adding an existing object member may replace it; array insertion shifts later elements.
remove and replace require the target path to exist.
move removes the value at from, then adds it at path; account for array index changes.
copy copies a value from a valid from path to path.
test compares the current value with value.
Paths and safe updates
Paths use JSON Pointer. A slash-separated token names an object member or array index; for example, /settings/theme points to theme inside settings. Escape a slash in a key as ~1 and a tilde as ~0. Array indexes start at zero; the dash token is used for appending only with add. Prefer a library that follows RFC 6901 over ad hoc string replacement.
Before sending, check that the server supports JSON Patch through API documentation or Allow/Accept-Patch. To apply changes only to the representation you read, send its strong ETag in If-Match when supported. If the ETag changed, reread and rebuild the patch. JSON Patch test is a document-level value precondition; If-Match conditions the HTTP representation version, so they serve different purposes.
The server must authorize every requested path and operation. Prevent access to forbidden fields even if a client changes the path, and set resource limits for large arrays or operation-heavy patches.
Sources
[RFC 6902: JSON Patch](https://www.rfc-editor.org/rfc/rfc6902.html)
[RFC 6901: JSON Pointer](https://www.rfc-editor.org/rfc/rfc6901.html)
[RFC 5789: PATCH Method for HTTP](https://www.rfc-editor.org/rfc/rfc5789.html)
[RFC 9110: HTTP Semantics](https://www.rfc-editor.org/rfc/rfc9110.html)