Standardadvanced
JSON Patch and JSON Merge Patch
Also called RFC 6902, RFC 7396, RFC 7386, merge patch, application/json-patch+json, application/merge-patch+json.
JSON Patch (RFC 6902) is a list of operations that change a JSON document. JSON Merge Patch (RFC 7396) is a partial document that is merged into the target. Both are bodies for HTTP PATCH.
What it is
JSON Patch and JSON Merge Patch are two formats that describe a change to a JSON document. A client sends the change instead of the full new document. Both formats were made for the HTTP method PATCH, which RFC 5789 defines to "apply partial modifications to a resource"1.
JSON Patch, defined in RFC 6902, is "a format (identified by the media type "application/json-patch+json") for expressing a sequence of operations to apply to a target JSON document"2. Each operation has a name, such as add or remove, and a target given as a JSON Pointer. The operations run in order, and the patch can test a value before it changes it.
JSON Merge Patch, defined in RFC 7396, is a partial copy of the document. It "describes changes to be made to a target JSON document using a syntax that closely mimics the document being modified"3. A member in the patch replaces or adds the member in the target, and a null removes it. The format is simple to read and write, but it cannot express every change.
| Property | JSON Patch2 | JSON Merge Patch3 |
|---|---|---|
| Media type | application/json-patch+json |
application/merge-patch+json |
| Form | an array of operation objects | a JSON value with the shape of the target |
| Arrays | insert, remove or move one element | replace the whole array |
Set a member to null |
yes, with add or replace |
no, null means remove |
| Conditions | the test operation |
none |
| Order of changes | the order of the operations | not significant |
Syntax or structure
A JSON Patch document "is a JSON [RFC4627] document that represents an array of objects"2. Each object has an op member and a path member. The value of op "MUST be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors"2, and path is a JSON Pointer2. Other members depend on the operation:
| Operation | Members | Effect2 |
|---|---|---|
add |
path, value |
inserts into an array, adds a new member, or replaces an existing member; - as the last token appends to an array |
remove |
path |
removes the value; the target must exist |
replace |
path, value |
the same as remove and then add at the same location; the target must exist |
move |
from, path |
the same as remove at from and then add at path; from must not be a prefix of path |
copy |
from, path |
the same as add at path with the value at from |
test |
path, value |
fails if the value at path is not equal to value |
The example patch of RFC 6902 shows all six operations:
[
{ "op": "test", "path": "/a/b/c", "value": "foo" },
{ "op": "remove", "path": "/a/b/c" },
{ "op": "add", "path": "/a/b/c", "value": [ "foo", "bar" ] },
{ "op": "replace", "path": "/a/b/c", "value": 42 },
{ "op": "move", "from": "/a/b/c", "path": "/a/b/d" },
{ "op": "copy", "from": "/a/b/d", "path": "/a/b/e" }
]
The operations apply "sequentially in the order they appear in the array", and each one sees the result of the one before it2. If an operation fails, evaluation "SHOULD terminate and application of the entire patch document SHALL NOT be deemed successful"2. Because PATCH in HTTP is atomic, a failed patch changes nothing21.
For test, two values are equal if they "are of the same JSON type" and equal under the rules of that type. Numbers are equal "if their values are numerically equal", arrays compare element by element in order, and the order of object members is not significant2.
A JSON Merge Patch is any JSON value. RFC 7396 defines its meaning with the function MergePatch3:
define MergePatch(Target, Patch):
if Patch is an Object:
if Target is not an Object:
Target = {} # Ignore the contents and set it to an empty Object
for each Name/Value pair in Patch:
if Value is null:
if Name exists in Target:
remove the Name/Value pair from Target
else:
Target[Name] = MergePatch(Target[Name], Value)
return Target
else:
return Patch
A patch that is not an object replaces the whole target. RFC 7396 says that it "is not possible to patch part of a target that is not an object, such as to replace just some of the values in an array"3.
Examples
The function apply_patch below implements the six operations of RFC 6902 in Python. It works on a deep copy, so a failed patch leaves the input as it was. The second patch is the example of section 5 of the RFC: the replace succeeds, the test fails, and the document does not change2.
import copy
import json
import re
INDEX = re.compile(r"0|[1-9][0-9]*")
class PatchError(Exception):
pass
def tokens(pointer):
if pointer == "":
return []
if not pointer.startswith("/"):
raise PatchError(f"bad pointer {pointer!r}")
return [t.replace("~1", "/").replace("~0", "~") for t in pointer[1:].split("/")]
def step(value, token):
if isinstance(value, dict) and token in value:
return value[token]
if isinstance(value, list) and INDEX.fullmatch(token) and int(token) < len(value):
return value[int(token)]
raise PatchError(f"no value at {token!r}")
def get(doc, pointer):
for token in tokens(pointer):
doc = step(doc, token)
return doc
def add(doc, pointer, value):
if pointer == "":
return value
*path, last = tokens(pointer)
container = doc
for token in path:
container = step(container, token)
if isinstance(container, dict):
container[last] = value
elif isinstance(container, list):
i = len(container) if last == "-" else int(last) if INDEX.fullmatch(last) else -1
if not 0 <= i <= len(container):
raise PatchError(f"bad index {last!r}")
container.insert(i, value)
else:
raise PatchError(f"cannot add to a {type(container).__name__}")
return doc
def remove(doc, pointer):
*path, last = tokens(pointer) or [None]
if last is None:
raise PatchError("cannot remove the root")
container = get(doc, "".join("/" + t.replace("~", "~0").replace("/", "~1") for t in path))
step(container, last) # The target must exist.
return container.pop(int(last) if isinstance(container, list) else last)
def equal(a, b):
"""The test rules of RFC 6902: the same JSON type, and equal values."""
if isinstance(a, bool) or isinstance(b, bool):
return type(a) is type(b) and a == b
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
return a == b
if type(a) is not type(b):
return False
if isinstance(a, list):
return len(a) == len(b) and all(map(equal, a, b))
if isinstance(a, dict):
return a.keys() == b.keys() and all(equal(a[k], b[k]) for k in a)
return a == b
def apply_patch(doc, patch):
"""Applies the operations in order to a copy, so a failed patch changes nothing."""
doc = copy.deepcopy(doc)
for op in patch:
kind, path = op["op"], op["path"]
if kind == "add":
doc = add(doc, path, copy.deepcopy(op["value"]))
elif kind == "remove":
remove(doc, path)
elif kind == "replace":
get(doc, path)
if path == "":
doc = copy.deepcopy(op["value"])
else:
remove(doc, path)
doc = add(doc, path, copy.deepcopy(op["value"]))
elif kind == "move":
if path.startswith(op["from"] + "/"):
raise PatchError("cannot move a value into its own child")
value = get(doc, op["from"])
if op["from"] != "":
remove(doc, op["from"])
doc = add(doc, path, value)
elif kind == "copy":
doc = add(doc, path, copy.deepcopy(get(doc, op["from"])))
elif kind == "test":
if not equal(get(doc, path), op["value"]):
raise PatchError(f"test failed at {path!r}")
else:
raise PatchError(f"unknown op {kind!r}")
return doc
doc = {"name": "lamp", "tags": ["home"], "stock": {"count": 3}}
patch = json.loads("""[
{"op": "test", "path": "/stock/count", "value": 3},
{"op": "replace", "path": "/stock/count", "value": 2},
{"op": "add", "path": "/tags/-", "value": "sale"},
{"op": "add", "path": "/tags/0", "value": "new"},
{"op": "copy", "from": "/name", "path": "/title"},
{"op": "move", "from": "/stock", "path": "/inventory"},
{"op": "remove", "path": "/name"}
]""")
print(json.dumps(apply_patch(doc, patch)))
bad = [{"op": "replace", "path": "/stock/count", "value": 42}, {"op": "test", "path": "/stock/count", "value": "C"}]
try:
apply_patch(doc, bad)
except PatchError as error:
print("PatchError:", error)
print(json.dumps(doc))
{"tags": ["new", "home", "sale"], "title": "lamp", "inventory": {"count": 2}}
PatchError: test failed at '/stock/count'
{"name": "lamp", "tags": ["home"], "stock": {"count": 3}}
merge_patch implements the MergePatch function. The input is the example of section 3 of RFC 7396: the patch changes title, adds phoneNumber, removes familyName and replaces the array tags3. The last line shows that a merge patch cannot store a null.
import json
def merge_patch(target, patch):
"""The MergePatch function of RFC 7396. It returns a new value."""
if not isinstance(patch, dict):
return patch
result = dict(target) if isinstance(target, dict) else {}
for name, value in patch.items():
if value is None:
result.pop(name, None)
else:
result[name] = merge_patch(result.get(name), value)
return result
target = json.loads("""{"title": "Goodbye!", "author": {"givenName": "John", "familyName": "Doe"},
"tags": ["example", "sample"], "content": "This will be unchanged"}""")
patch = json.loads("""{"title": "Hello!", "phoneNumber": "+01-123-456-7890",
"author": {"familyName": null}, "tags": ["example"]}""")
print(json.dumps(merge_patch(target, patch)))
# A merge patch cannot set a member to null: null means "remove".
print(json.dumps(merge_patch({"a": 1}, {"a": None})))
{"title": "Hello!", "author": {"givenName": "John"}, "tags": ["example"], "content": "This will be unchanged", "phoneNumber": "+01-123-456-7890"}
{}
The example files of this page show more:
- JavaScript. A merge patch made from two versions of a document, and applied again.
- Go. A merge patch on decoded maps, and the reason that a struct cannot hold a merge patch: a
nilpointer field does not tell{"note": null}from{}. - C#. The
testoperation withJsonNode.DeepEquals, which "Compares the values of two nodes, including the values of all descendant nodes"4.
using System.Text.Json.Nodes;
JsonNode doc = JsonNode.Parse("""{"price": 10, "active": true, "tags": ["a", "b"]}""")!;
string[] patches =
[
"""[{"op": "test", "path": "/price", "value": 10.0}, {"op": "replace", "path": "/price", "value": 12}]""",
"""[{"op": "test", "path": "/active", "value": 1}, {"op": "replace", "path": "/active", "value": false}]""",
"""[{"op": "test", "path": "/tags", "value": ["b", "a"]}]""",
];
foreach (string text in patches)
{
try
{
doc = Apply(doc, JsonNode.Parse(text)!.AsArray());
Console.WriteLine($"ok {doc.ToJsonString()}");
}
catch (InvalidOperationException e)
{
Console.WriteLine($"error {e.Message}");
}
}
// Apply runs the test and replace operations of RFC 6902 on a copy of doc.
static JsonNode Apply(JsonNode doc, JsonArray patch)
{
JsonNode result = doc.DeepClone();
foreach (JsonNode? op in patch)
{
string path = (string)op!["path"]!;
JsonObject parent = result.AsObject();
string name = path[1..];
if (!parent.TryGetPropertyValue(name, out JsonNode? current))
throw new InvalidOperationException($"no value at {path}");
switch ((string)op["op"]!)
{
case "test":
if (!JsonNode.DeepEquals(current, op["value"]))
throw new InvalidOperationException($"test failed at {path}");
break;
case "replace":
parent[name] = op["value"]?.DeepClone();
break;
default:
throw new InvalidOperationException("this example has only test and replace");
}
}
return result;
}
ok {"price":12,"active":true,"tags":["a","b"]}
error test failed at /active
error test failed at /tags
- Verdict: stdlib.
System.Text.Json.Nodesparses the document and the patch into nodes, andDeepClonegives the copy that the operations change, so a failed patch leavesdocas it was.JsonNode.DeepEquals"Compares the values of two nodes, including the values of all descendant nodes". In the run it treats10and10.0as equal, it does not treattrueand1as equal, and it compares array elements in order. These are the results that thetestrules of RFC 6902 require. .NET has no JSON Patch type in the base library, so the example handles onlytestandreplaceon members of the root object. For a full implementation, ASP.NET Core web APIs use the NuGet packageMicrosoft.AspNetCore.JsonPatch.SystemTextJson.
const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
// mergePatch applies an RFC 7396 merge patch and returns a new value.
function mergePatch(target, patch) {
if (!isObject(patch)) return patch;
const result = isObject(target) ? { ...target } : {};
for (const [name, value] of Object.entries(patch)) {
if (value === null) delete result[name];
else result[name] = mergePatch(result[name], value);
}
return result;
}
// makeMergePatch returns a merge patch that turns before into after.
function makeMergePatch(before, after) {
if (!isObject(before) || !isObject(after)) return after;
const patch = {};
for (const name of Object.keys(before)) {
if (!Object.hasOwn(after, name)) patch[name] = null;
}
for (const [name, value] of Object.entries(after)) {
if (!Object.hasOwn(before, name)) patch[name] = value;
else if (JSON.stringify(before[name]) !== JSON.stringify(value)) {
patch[name] = makeMergePatch(before[name], value);
}
}
return patch;
}
const before = { id: 7, name: "lamp", tags: ["home", "sale"], size: { w: 20, h: 40 } };
const after = { id: 7, name: "desk lamp", tags: ["home"], size: { w: 20, h: 45 } };
const patch = makeMergePatch(before, after);
console.log(JSON.stringify(patch));
console.log(JSON.stringify(mergePatch(before, patch)) === JSON.stringify(after));
// An array is replaced as a whole, and null always removes a member.
console.log(JSON.stringify(mergePatch({ tags: ["a", "b"] }, { tags: ["c"] })));
console.log(JSON.stringify(makeMergePatch({ note: "x" }, { note: null })));
console.log(JSON.stringify(mergePatch({ note: "x" }, makeMergePatch({ note: "x" }, { note: null }))));
{"name":"desk lamp","tags":["home"],"size":{"h":45}}
true
{"tags":["c"]}
{"note":null}
{}
- Verdict: native. A merge patch is plain JSON, so
JSON.parseand object spread are all the code needs.mergePatchfollows the MergePatch function of RFC 7396 and returns a new object.makeMergePatchgoes the other way: it compares two documents and writesnullfor each member that is gone. The last three lines show the limits of the format. An array is replaced as a whole, and a member with the valuenullcannot be set, because the patch{"note":null}removes the member.
package main
import (
"encoding/json"
"fmt"
)
// mergePatch applies an RFC 7396 merge patch to a decoded JSON value.
func mergePatch(target, patch any) any {
p, ok := patch.(map[string]any)
if !ok {
return patch
}
result := map[string]any{}
if t, ok := target.(map[string]any); ok {
for k, v := range t {
result[k] = v
}
}
for name, value := range p {
if value == nil {
delete(result, name)
} else {
result[name] = mergePatch(result[name], value)
}
}
return result
}
func main() {
var target, patch any
json.Unmarshal([]byte(`{"name": "lamp", "note": "fragile", "size": {"w": 20, "h": 40}}`), &target)
json.Unmarshal([]byte(`{"note": null, "size": {"h": 45}, "color": "red"}`), &patch)
out, _ := json.Marshal(mergePatch(target, patch)) // Marshal sorts the keys of a map.
fmt.Println(string(out))
// A struct field cannot tell a member with the value null from a member that is not there.
type Update struct {
Note *string `json:"note"`
}
for _, body := range []string{`{"note": null}`, `{}`} {
var u Update
json.Unmarshal([]byte(body), &u)
var m map[string]json.RawMessage
json.Unmarshal([]byte(body), &m)
raw, present := m["note"]
fmt.Printf("%-16s struct field nil: %v, map member present: %v %q\n", body, u.Note == nil, present, string(raw))
}
}
{"color":"red","name":"lamp","size":{"h":45,"w":20}}
{"note": null} struct field nil: true, map member present: true "null"
{} struct field nil: true, map member present: false ""
- Verdict: stdlib.
json.Unmarshalintoanygivesmap[string]anyfor objects andnilfornull, somergePatchfollows RFC 7396 directly. The second part shows a trap for a PATCH handler in Go. A pointer field in a struct isnilboth for{"note": null}and for{}, so the handler cannot tell "remove the note" from "keep the note". Amap[string]json.RawMessagekeeps the difference: the member is present, and its raw text isnull.
Versions
RFC 6902 (JSON Patch) and RFC 6901 (JSON Pointer) were published together in April 201325. Neither has a later version.
JSON Merge Patch was first published as RFC 7386 in October 20146. RFC 7396 replaced it in the same month, and its header says "Obsoletes: 7386"3. The two texts have the same MergePatch steps, but in the text of RFC 7386 some lines of the pseudocode have the wrong indentation63. Use RFC 7396.
Pitfalls
- A naive
testcompares the wrong types. In Python,True == 1is true, so atestthat uses==accepts1fortrue. RFC 6902 requires the same JSON type2:
This code runs but gives a wrong answer on purpose.
# A test operation that compares with == accepts values of the wrong JSON type.
print(True == 1, [1, 0] == [True, False], {"on": 1} == {"on": True})
True True True
The equal function of the example checks for bool before it compares numbers.
- A partial apply. An implementation that changes the document in place and stops at the first error leaves a document that is neither the old one nor the new one. Apply the operations to a copy, or undo them, so the patch is atomic2.
- Array indexes move. After
addat/tags/0, every later index in the same array is one larger, because the elements "are shifted one position to the right"2. A patch that a program writes must use the indexes of the document at that step, not of the original. Atestbefore a change finds a wrong index early. addon a missing parent.addcreates the last member only. RFC 6902 says that theaddto/a/bis an error on{ "q": { "bar": 2 } }, "because "a" does not exist"2.nullin a merge patch. A merge patch cannot give a member the valuenull, and RFC 7396 says that the format suits documents that "do not make use of explicit null values"3. Use JSON Patch whennullis a real value.- Arrays in a merge patch. A merge patch replaces a whole array. Two clients that each add one element to the same array lose one change. Use JSON Patch with
-to append. - The wrong media type. A server must know which format the body uses. Send
application/json-patch+jsonorapplication/merge-patch+json, notapplication/json23. - Lost updates. A patch applies to the current state of a resource. RFC 6902 shows the request with an
If-Matchheader2, so the server applies the patch only to the version that the client saw.
Tools and libraries
- Python: the library
jsonpatch.jsonpatch.make_patch(src, dst)makes a patch from two documents, andjsonpatch.apply_patch(obj, patch)applies one7. - Java: the interface
jakarta.json.JsonPatchof Jakarta JSON Processing.Json.createPatch(JsonArray)makes a patch, andapplyapplies it8. - C#: ASP.NET Core web APIs read JSON Patch requests with the NuGet package
Microsoft.AspNetCore.JsonPatch.SystemTextJson9. - JavaScript and Go: the merge patch function is short, as in the examples. JSON Patch needs a library or a resolver such as the one on JSON Pointer.
References
- L. Dusseault, J. Snell, RFC 5789: PATCH Method for HTTP, March 2010, 2 The PATCH Method; 2.2 Error Handling
- P. Bryan (Ed.), M. Nottingham (Ed.), RFC 6902: JavaScript Object Notation (JSON) Patch, April 2013, 1 Introduction; 3 Document Structure; 4 Operations; 4.1 to 4.6; 5 Error Handling; 6 IANA Considerations
- P. Hoffman, J. Snell, RFC 7396: JSON Merge Patch, October 2014, 1 Introduction; 2 Processing Merge Patch Documents; 3 Example; Appendix A Example Test Cases
- .NET API reference, JsonNode.DeepEquals, the method description
- P. Bryan (Ed.), K. Zyp, M. Nottingham (Ed.), RFC 6901: JavaScript Object Notation (JSON) Pointer, April 2013, 4 Evaluation
- P. Hoffman, J. Snell, RFC 7386: JSON Merge Patch, October 2014 (obsoleted by RFC 7396), 2 Processing Merge Patch Documents
- python-json-patch documentation, Tutorial, Creating a Patch; Applying a Patch
- Jakarta JSON Processing 2.1 API, interface JsonPatch, the interface description
- Microsoft Learn, JSON Patch support in ASP.NET Core web API, the introduction
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 3J41ZW Edit this page History Report an error Markdown