stefankoegl / python-json-patch

Applying JSON Patches in Python
https://python-json-patch.readthedocs.org/
BSD 3-Clause "New" or "Revised" License
434 stars 94 forks source link

Changes don't have a structured order #121

Closed tomking2 closed 3 years ago

tomking2 commented 3 years ago

From what it seems, changes do not have a structured order to them, making it difficult to ensure you can apply/revert patches.

Take the following example:

import jsonpatch

data1 = {'field': ["one", "two", "three", "four", "five"]}
data2 = {'field': ["one", "one_one", "two", "four", "three"]}

forward_change = jsonpatch.make_patch(data1, data2)
reverse_change = jsonpatch.make_patch(data2, data1)

This ends up with the following changes

Forward:
[{'op': 'add', 'path': '/field/1', 'value': 'one_one'}, {'op': 'remove', 'path': '/field/5'}, {'op': 'move', 'from': '/field/3', 'path': '/field/4'}]

Reverse:
[{'op': 'remove', 'path': '/field/1'}, {'op': 'move', 'from': '/field/3', 'path': '/field/2'}, {'op': 'add', 'path': '/field/4', 'value': 'five'}]

Now, just applying the patch is straightforward, you can apply the forward_change to manipulate data1 to be data2, and manipulate data2 to be data1. However, I've implemented a mechanism to remove a patch; this could be intermediary between numerous patches. Subsequent patches are re-adjusted to reflect the removal of a earlier patch.

To do this, I was hoping that index[0] of forward_change.patch (fp) is the direct opposite of index[0] of reverse_change.patch (rp), However, the current index output is:

fp0 = rp0
fr1 = rp2
fr2 = rp1

At least in this use case, the position of the incorrectly ordered index is irrelevant; the correct apply_patch change will be made regardless of whether index 1 and 2 are the right/wrong way round.

I couldn't spot any hardcoded reason for the position of the patch items. Is there a reason you can think of for this, or a possible approach to fix up the order?