Registry / serialization / jsonpatch

jsonpatch

JSON →
library1.33pypypi✓ verified 25d ago

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.

pip install jsonpatch
INSTALL
IMPORT
SIG · JSONPATCH
J
jsonpatch
serializationpythonv1.33
Install
1.8s avg
Import
10ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.33 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.010s · 17.9MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.8s · import 0.010s · 18MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

JsonPatch
from jsonpatch import JsonPatch
JsonPointerException
from jsonpatch import JsonPointerException
Raised when a patch operation encounters a conflict or error.
apply_patch
from jsonpatch import apply_patch
A convenience function to apply a patch to a document.
make_patch
from jsonpatch import make_patch
A convenience function to generate a patch by diffing two documents.

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.
Debug
Known issues
gotchaThe `apply` method returns a *new* modified object by default, leaving the original document unchanged. If you intend to modify the document in-place, you must explicitly pass `in_place=True` to the `apply` method.
fix
Use `result = patch.apply(original_doc)` for a new object, or `patch.apply(original_doc, in_place=True)` to modify the original.
affects: All versions
gotchaJSON Pointer (RFC 6901), used for `path` in operations, requires special characters `~` and `/` within object keys to be escaped as `~0` and `~1` respectively. Additionally, the empty string `""` refers to the root of the document, while `/` refers to a key named `""` at the root.
fix
Ensure JSON Pointers correctly escape special characters in path segments (e.g., `/foo~1bar` for key `foo/bar`) and use `""` for the document root.
affects: All versions
gotchaWhen modifying arrays, `add` operations support the special character `-` in the path (e.g., `/array/-`) to append a value to the end of the array. However, `remove` or `replace` operations typically require a numeric index. Relying on fixed indices for modifications can be fragile if the array's order or content might change unpredictably between patch generation and application.
fix
For `add` to end of array, use `/array/-`. For `remove`/`replace`, use explicit indices like `/array/0`. Be mindful of array stability when patching by index.
affects: All versions
gotchaJSON Patch operations are atomic. If any single operation within a patch document fails (e.g., a `test` operation fails, or a `remove` operation targets a non-existent path), a `jsonpatch.JsonPointerException` will be raised. If `in_place=False` (the default), no changes will be applied. If `in_place=True`, the state after an error is undefined and may be partially applied.
fix
Implement robust error handling for `JsonPointerException` when applying patches. If modifying in-place, consider applying patches within a transaction or to a copy first if atomicity is critical.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'jsonpatch'
The 'jsonpatch' Python package is not installed in your current environment or is not accessible in your Python path.
fix
Install the library using pip: `pip install jsonpatch`
AttributeError: 'list' object has no attribute 'items'
This error occurs when attempting to call the `.items()` method (which is designed for dictionaries) on a Python list object. This often happens when a JSON document is parsed into a list (e.g., a JSON array at the root) but is then treated as a dictionary, or when iterating over a list of dictionaries without accessing individual dictionary elements first.
fix
Ensure the object you are calling `.items()` on is a dictionary. If it's a list of dictionaries, iterate through the list and apply `.items()` to each dictionary: `for item in my_list: for key, value in item.items(): ...`
jsonpatch.JsonPatchException: Patch could not be applied due to conflict situation
This general exception is raised by the `jsonpatch` library when an operation within the patch document cannot be successfully applied to the target JSON document. Common reasons include attempting to add a key that already exists, operating on a non-existent path (e.g., trying to modify a property whose parent object doesn't exist), or inserting a value into an array at an out-of-bounds position.
fix
Review the patch operations and the target document. Ensure all paths specified in the patch exist or are valid for the intended operation (e.g., parent objects for 'add' operations must exist). Validate array indices and avoid attempting to add keys that already exist.
jsonpatch.JsonPointerException: Key 'nonexistent_key' not found in document
This specific exception indicates that a JSON Pointer path used in a patch operation attempts to access a key or array index that does not exist in the target document. For instance, an 'add' operation might try to create a property at `/a/b/c` when `/a/b` does not exist.
fix
Ensure all intermediate components of a JSON Pointer path exist in the target document before attempting operations like 'remove', 'replace', or 'test'. For 'add' operations, the *parent* path must exist; if intermediate objects need to be created, they must be added incrementally as separate operations.
Upgrade
Version history
1.33latest on PyPI · released Jun 16, 2023
Audit
Dependencies

No dependency data recorded yet.

Agent activity
7 hits · last 30 days
node
6
Resources
jsonpatch — pip install jsonpatch · libregistry