Skip to content


void merge_patch(const basic_json& apply_patch);

The merge patch format is primarily intended for use with the HTTP PATCH method as a means of describing a set of modifications to a target resource's content. This function applies a merge patch to the current JSON value.

The function implements the following algorithm from Section 2 of RFC 7396 (JSON Merge Patch):

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
        Target[Name] = MergePatch(Target[Name], Value)
    return Target
    return Patch

Thereby, Target is the current object; that is, the patch is applied to the current value.


apply_patch (in)
the patch to apply


Linear in the lengths of apply_patch.



The following code shows how a JSON Merge Patch is applied to a JSON document.

#include <iostream>
#include <nlohmann/json.hpp>
#include <iomanip> // for std::setw

using json = nlohmann::json;
using namespace nlohmann::literals;

int main()
    // the original document
    json document = R"({
                "title": "Goodbye!",
                "author": {
                    "givenName": "John",
                    "familyName": "Doe"
                "tags": [
                "content": "This will be unchanged"

    // the patch
    json patch = R"({
                "title": "Hello!",
                "phoneNumber": "+01-123-456-7890",
                "author": {
                    "familyName": null
                "tags": [

    // apply the patch

    // output original and patched document
    std::cout << std::setw(4) << document << std::endl;


    "author": {
        "givenName": "John"
    "content": "This will be unchanged",
    "phoneNumber": "+01-123-456-7890",
    "tags": [
    "title": "Hello!"

See also

Version history

  • Added in version 3.0.0.

Last update: May 1, 2022