JSON Patch (RFC 6902) restricted to add, remove and replace
(Effect's JsonPatch): get computes a patch between two JSON values,
apply runs one without mutating its input::
patch = json_patch.get({"a": 1}, {"a": 2, "b": [1]})
# [{"op": "replace", "path": "/a", "value": 2}, {"op": "add", "path": "/b", "value": [1]}]
json_patch.apply(patch, {"a": 1}) # {"a": 2, "b": [1]}Arrays are lists or tuples and objects string-keyed mappings on the way in;
apply builds new lists and dicts along the path it changes and keeps
every other value as it is. An operation that does not fit the value raises
ValueError with Effect's message; a value that is not a patch (not a
list of objects with a string path, or an add or replace with no
value) raises TypeError, as Effect's does. As in Effect, an op
other than add or remove is a replace: test is not checked.
Re-exports#
- From
pyfect.schema:JsonValue
Types#
| Type | Definition | Description |
|---|---|---|
JsonPatchOperation | type JsonPatchOperation = AddOperation | RemoveOperation | ReplaceOperation | |
JsonPatch | type JsonPatch = Sequence[JsonPatchOperation] |
Classes#
Functions#
get#
get(old_value, new_value) -> list[JsonPatchOperation]The operations turning old_value into new_value: array
elements compared by index (removals from the end first, then
additions), object keys in JavaScript's sorted order, anything else a replace.
| Parameter | Type | Description |
|---|---|---|
old_value | JsonValue | |
new_value | JsonValue |
Returns list[JsonPatchOperation]
def get(old_value: JsonValue, new_value: JsonValue) -> list[JsonPatchOperation]:
"""The operations turning ``old_value`` into ``new_value``: array
elements compared by index (removals from the end first, then
additions), object keys in JavaScript's sorted order, anything else a ``replace``."""
patches: list[JsonPatchOperation] = []
_get_loop(old_value, new_value, "", patches)
return patchesapply#
apply(patch, old_value) -> JsonValueold_value with each operation applied in order. An empty patch
returns old_value itself. As in Effect, an operation whose op is
not add or remove (test, a typo, none) is a replace.
| Parameter | Type | Description |
|---|---|---|
patch | JsonPatch | |
old_value | JsonValue |
Returns JsonValue
def apply(patch: JsonPatch, old_value: JsonValue) -> JsonValue:
"""``old_value`` with each operation applied in order. An empty patch
returns ``old_value`` itself. As in Effect, an operation whose ``op`` is
not ``add`` or ``remove`` (``test``, a typo, none) is a ``replace``."""
doc = old_value
owned = _Owned()
for operation in patch:
doc = _apply_operation(doc, _parse_operation(operation), owned)
return doc