JSON Patch

1.33 · active · verified Sat Mar 28

jsonpatch is a Python library for applying JSON Patches (RFC 6902), a standard format for describing changes to a JSON document. It provides functionalities to create, apply, and generate patches by diffing two JSON objects. The library is actively maintained, with its current version being 1.33.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a `JsonPatch` object from a list of operations and apply it to a document, as well as how to use `make_patch` to generate a patch by comparing two documents. The `apply` method returns a new modified document by default.

import jsonpatch

# Original document
doc = {"baz": "qux", "foo": "bar", "numbers": [1, 3, 4, 8]}

# 1. Define a patch explicitly
patch_ops = [
    {"op": "replace", "path": "/baz", "value": "boo"},
    {"op": "add", "path": "/hello", "value": ["world"]},
    {"op": "remove", "path": "/foo"},
    {"op": "replace", "path": "/numbers/0", "value": 0}, # Replace first element
    {"op": "add", "path": "/numbers/-", "value": 99} # Add to end of array
]
patch = jsonpatch.JsonPatch(patch_ops)

# Apply the patch (returns a new object by default)
result = patch.apply(doc)
print("1. Applied patch result:", result)
# Expected: {'baz': 'boo', 'numbers': [0, 3, 4, 8, 99], 'hello': ['world']}

# 2. Generate a patch by diffing two objects
old_doc = {"a": 1, "b": 2, "c": {"d": 3}}
new_doc = {"a": 10, "c": {"e": 5}, "f": 6}
diff_patch = jsonpatch.make_patch(old_doc, new_doc)
print("2. Generated diff patch operations:", diff_patch.patch)
# Expected operations will modify old_doc to become new_doc.

view raw JSON →