stefankoegl / python-json-patch

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

make_patch cannot handle addition of nested dictionaries #66

Closed zauberparacelsus closed 7 years ago

zauberparacelsus commented 7 years ago

make_patch fails when you add a dictionary object as an element to another existing dictionary.

The following code will reproduce the problem, with the output being an empty list:

import jsonpatch
sourceData = {"foo": {}}
output = dict(sourceData)
output["foo"]["bar"] = {"a": 1, "b": 2, "c": 3}
print(jsonpatch.make_patch(sourceData, output))
stefankoegl commented 7 years ago

What you're describing is not an issue with jsonpatch.

import jsonpatch
sourceData = {"foo": {}}
output = dict(sourceData)

You have made a shallow copy of sourceData. Any change to the inner dict of output will also be present in sourceData.

output["foo"]["bar"] = {"a": 1, "b": 2, "c": 3}

Let's check sourceData:

>>> sourceData
{'foo': {'bar': {'b': 2, 'a': 1, 'c': 3}}}

So sourceData and output are now equal, and therefore the produced patch is empty.

If you'd do the following instead, it would work as expected.

>>> import jsonpatch
>>> sourceData = {"foo": {}}
>>> output = {"foo": {"bar": {"a": 1, "b": 2, "c": 3}}}
>>> print(jsonpatch.make_patch(sourceData, output))
[{"value": {"b": 2, "a": 1, "c": 3}, "op": "add", "path": "/foo/bar"}]