2ClickKit

JSON Patch & Merge Tool (RFC 6902)

Apply RFC 6902 operations, generate differential patches between documents, or execute RFC 7396 Merge Patches directly in your browser.

Applying sequential operations (add, remove, replace, move, copy, test)
Original JSON Document
RFC Patch Document
Patched OutputApplied 4 operations successfully

Engineering Guide: JSON Patch, Merge Patch, and RFC Specifications

Modern distributed architectures, microservices, and RESTful APIs rely heavily on JSON for data exchange. While the HTTP PUT method allows clients to replace an entire resource representation, it introduces substantial bandwidth overhead and concurrency conflicts when only small subsets of a resource change. To address partial resource updates, the Internet Engineering Task Force (IETF) standardized two complementary specifications: RFC 6902 (JavaScript Object Notation (JSON) Patch) and RFC 7396 (JSON Merge Patch).

Understanding the operational mechanics, formal grammar, serialization guarantees, and algorithmic trade-offs between these two standards is critical for software architects designing resilient distributed systems.

1. RFC 6902: Atomic Operation Sequences

RFC 6902 defines a JSON document format representing a sequence of operations to be applied to a target JSON document. A JSON Patch document is always formatted as a JSON array containing zero or more operation objects. Each operation object must contain an op member indicating the operation type, a path member indicating the target location via an RFC 6901 JSON Pointer, and optional value or from members depending on the specific operation.

The Six Fundamental Operations

2. RFC 6901: JSON Pointer Syntax and Traversal

JSON Pointer defines a string syntax for identifying a specific value within a JSON document. A pointer consists of a sequence of zero or more reference tokens, each prefixed by a forward slash (/). Traversal begins at the document root:

Escape Characters in JSON Pointer

Because the forward slash separates path tokens, object keys that contain literal slashes or tildes require escaping:

Literal Character in Key Encoded Token Sequence Example Property Name Equivalent JSON Pointer
Tilde (~) ~0 user~profile /user~0profile
Forward Slash (/) ~1 billing/address /billing~1address
Both (~/) ~0~1 a~/b /a~0~1b

3. RFC 7396: JSON Merge Patch

While RFC 6902 provides granular transactional precision, its verbose array-of-objects structure can feel heavyweight for simple CRUD operations. RFC 7396 was created as an intuitive alternative that models the patch payload to resemble the resource itself.

The merge patch algorithm is formally defined recursively as follows:

  1. If the patch is not a JSON object, the target document is completely replaced by the patch.
  2. If the patch is a JSON object, iterate over each member key-value pair:
    • If the patch value is null, remove the corresponding key from the target object if it exists.
    • If the patch value is another JSON object, recursively apply the merge patch to the corresponding target property.
    • Otherwise, overwrite the target property with the patch value.

The Array Limitation of RFC 7396

The primary operational limitation of RFC 7396 is its inability to partially manipulate arrays. Because arrays in RFC 7396 are treated as primitive scalar replacements, appending, removing, or reordering a single item in an array requires serializing the entire modified array in the patch document. If your domain model requires fine-grained mutations of large collections, RFC 6902 is strictly superior.

4. Comparative Technical Analysis: RFC 6902 vs. RFC 7396

Architectural Criterion RFC 6902 (JSON Patch) RFC 7396 (JSON Merge Patch)
MIME Media Type application/json-patch+json application/merge-patch+json
Atomicity Guarantee Full (all operations succeed or entire document rolls back) Implicit recursive application
Precondition Testing Built-in via test operation None (requires external ETags / If-Match headers)
Array Modification Item-level insertion, deletion, and index shifting Total array replacement only
Null Value Handling Can explicitly set values to null null triggers field deletion (cannot store literal nulls easily)
Implementation Complexity Moderate (state machine, pointer escaping, index tracking) Low (straightforward recursive object walk)

5. Differential Patch Generation Algorithms

Generating an RFC 6902 patch from an original document A to a modified document B involves structural subtree diffing. A production-grade diff engine traverses the JSON object tree using the following heuristics:

6. RESTful API Best Practices and Optimistic Concurrency

When exposing HTTP PATCH endpoints in distributed environments, concurrency anomalies are a frequent vulnerability. Multiple clients may fetch resource version 1 and attempt to apply independent patches simultaneously. Without concurrency safeguards, the second client may overwrite changes applied by the first.

Two primary strategies mitigate this issue:

  1. HTTP Entity Tags (ETags): The server returns an ETag: "v1" header with GET responses. Clients must supply this value in an If-Match: "v1" header when issuing a PATCH request. If another transaction has modified the entity, the server returns HTTP 412 Precondition Failed.
  2. RFC 6902 In-Band Test Operations: Clients can prepend a test operation to their patch document:
    [
      { "op": "test", "path": "/version", "value": 4 },
      { "op": "replace", "path": "/status", "value": "APPROVED" },
      { "op": "replace", "path": "/version", "value": 5 }
    ]
    If another worker modified /version between the read and write phases, the patch execution halts immediately, guaranteeing zero partial writes.

Frequently Asked Questions

What is the difference between RFC 6902 JSON Patch and RFC 7396 Merge Patch?

RFC 6902 defines a sequence of discrete operations (add, remove, replace, move, copy, and test) executed sequentially on target paths designated by RFC 6901 JSON Pointers. It supports array manipulation and atomic preconditions. RFC 7396 Merge Patch describes changes as a delta JSON object where matching keys are replaced, null values represent key deletions, and undefined keys remain untouched. RFC 7396 is simpler but cannot delete array items without replacing the entire array.

How does RFC 6901 JSON Pointer handle special characters like slashes and tildes?

In RFC 6901, the forward slash (/) acts as a path delimiter between object keys and array indices. To represent a literal slash within a key name, it is escaped as ~1. To represent a literal tilde (~), it is escaped as ~0. The escaping must be evaluated in order: replace ~1 first, then replace ~0.

What is the purpose of the 'test' operation in RFC 6902?

The 'test' operation verifies that a value at a specified path matches an expected value before subsequent modifications are applied. If the test fails, the patch transaction is aborted entirely, ensuring optimistic concurrency control and preventing stale writes in distributed HTTP PATCH endpoints.

How do array indices work in RFC 6902 paths?

Array elements are addressed using zero-based integer strings (such as /items/0 or /items/3). The special index character '-' (hyphen), as in /items/-, refers to the position immediately after the last element of the array, which is used with the 'add' operation to append new items.

Can I generate a JSON Patch diff between two arbitrary JSON objects?

Yes. This tool provides a two-way JSON diff generator. It recursively compares original and modified documents, producing a minimal list of standard RFC 6902 operations (add, remove, replace) required to transform the original document into the modified target.

Is my data sent to any remote server when using this tool?

No. All diffing, patching, pointer resolutions, and RFC 7396 merge operations run entirely within your browser runtime using client-side JavaScript. No payload strings or patch manifests are ever transmitted over the network.

Why is HTTP PATCH preferred over HTTP PUT for partial updates?

HTTP PUT requires sending the complete representation of the modified resource, which consumes high bandwidth and is prone to lost updates when concurrent clients overwrite each other. HTTP PATCH sends only the semantic delta, significantly reducing payload size and allowing atomic validation through patch operations.