Skip to main content

2. Processing Merge Patch Documents

2. Processing Merge Patch Documents

JSON merge patch documents describe, by example, a set of changes that are to be made to a target resource. Recipients of merge patch documents are responsible for comparing the merge patch with the current content of the target resource to determine the specific set of change operations to be applied to the target.

To apply the merge patch document to a target resource, the system realizes the effect of the following function, described in pseudocode. For this description, the function is called MergePatch, and it takes two arguments: the target resource document and the merge patch document. The Target argument can be any JSON value or undefined. The Patch argument can be any JSON value.

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

There are a few things to note about the function. If the patch is anything other than an object, the result will always be to replace the entire target with the entire patch. Also, 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.

The MergePatch operation is defined to operate at the level of data items, not at the level of textual representation. There is no expectation that the MergePatch operation will preserve features at the textual-representation level such as white space, member ordering, number precision beyond what is available in the target's implementation, and so forth. In addition, even if the target implementation allows multiple name/value pairs with the same name, the result of the MergePatch operation on such objects is not defined.