JSON Merge Patch

0.3.0 · active · verified Thu Apr 09

This library provides functions to merge JSON documents in accordance with RFC 7386, the JSON Merge Patch standard. It offers a simpler alternative to JSON Patch for updating JSON resources, especially for object-based modifications. The current version is 0.3.0, with a focus on implementing the standard without external dependencies beyond the standard library.

Warnings

Install

Imports

Quickstart

This example demonstrates how to apply a JSON merge patch to a document and how to generate a patch document by comparing an original and a target document. Note that the library expects and returns Python dictionaries; JSON serialization/deserialization is the user's responsibility.

import json
import json_merge_patch

document = {"a": 1, "b": 2, "c": {"d": 4}}
patch = {"a": 2, "c": {"e": 5}, "f": None}

# Applying a merge patch
# 'f': None in patch implies deletion of 'f' if it existed, otherwise ignored
# 'c': {'e': 5} replaces the entire 'c' object
result = json_merge_patch.merge(document, patch)
print(f"Merged result: {json.dumps(result, indent=2)}")
# Expected output: {'a': 2, 'b': 2, 'c': {'e': 5}}

original = {"name": "Alice", "details": {"age": 30, "city": "NY"}, "tags": ["A", "B"]}
target = {"name": "Bob", "details": {"age": 31}, "email": "bob@example.com", "tags": ["C"]}

# Creating a merge patch
# 'name': 'Bob' replaces 'Alice'
# 'details': {'age': 31} replaces the entire 'details' object (city is removed)
# 'email': 'bob@example.com' is added
# 'tags': ['C'] replaces the entire 'tags' array
patch_doc = json_merge_patch.create_patch(original, target)
print(f"Generated patch: {json.dumps(patch_doc, indent=2)}")
# Expected output: {'name': 'Bob', 'details': {'age': 31}, 'email': 'bob@example.com', 'tags': ['C']}

view raw JSON →