Let apply_patch to handle patch as JSON-encoded string.
This commit is contained in:
10
jsonpatch.py
10
jsonpatch.py
@@ -47,6 +47,9 @@ if sys.version_info < (2, 6):
|
|||||||
else:
|
else:
|
||||||
import json
|
import json
|
||||||
|
|
||||||
|
if sys.version_info >= (3, 0):
|
||||||
|
basestring = (bytes, str)
|
||||||
|
|
||||||
|
|
||||||
class JsonPatchException(Exception):
|
class JsonPatchException(Exception):
|
||||||
"""Base Json Patch exception"""
|
"""Base Json Patch exception"""
|
||||||
@@ -67,7 +70,7 @@ def apply_patch(doc, patch, in_place=False):
|
|||||||
:param doc: Document object.
|
:param doc: Document object.
|
||||||
:type doc: dict
|
:type doc: dict
|
||||||
|
|
||||||
:param patch: JSON patch as list of dicts.
|
:param patch: JSON patch as list of dicts or raw JSON-encoded string.
|
||||||
:type patch: list
|
:type patch: list
|
||||||
|
|
||||||
:param in_place: While :const:`True` patch will modify target document.
|
:param in_place: While :const:`True` patch will modify target document.
|
||||||
@@ -89,7 +92,10 @@ def apply_patch(doc, patch, in_place=False):
|
|||||||
True
|
True
|
||||||
"""
|
"""
|
||||||
|
|
||||||
patch = JsonPatch(patch)
|
if isinstance(patch, basestring):
|
||||||
|
patch = JsonPatch.from_string(patch)
|
||||||
|
else:
|
||||||
|
patch = JsonPatch(patch)
|
||||||
return patch.apply(doc, in_place)
|
return patch.apply(doc, in_place)
|
||||||
|
|
||||||
def make_patch(src, dst):
|
def make_patch(src, dst):
|
||||||
|
|||||||
8
tests.py
8
tests.py
@@ -8,6 +8,14 @@ import jsonpatch
|
|||||||
|
|
||||||
class ApplyPatchTestCase(unittest.TestCase):
|
class ApplyPatchTestCase(unittest.TestCase):
|
||||||
|
|
||||||
|
def test_apply_patch_from_string(self):
|
||||||
|
obj = {'foo': 'bar'}
|
||||||
|
patch = '[{"add": "/baz", "value": "qux"}]'
|
||||||
|
res = jsonpatch.apply_patch(obj, patch)
|
||||||
|
self.assertTrue(obj is not res)
|
||||||
|
self.assertTrue('baz' in res)
|
||||||
|
self.assertEqual(res['baz'], 'qux')
|
||||||
|
|
||||||
def test_apply_patch_to_copy(self):
|
def test_apply_patch_to_copy(self):
|
||||||
obj = {'foo': 'bar'}
|
obj = {'foo': 'bar'}
|
||||||
res = jsonpatch.apply_patch(obj, [{'add': '/baz', 'value': 'qux'}])
|
res = jsonpatch.apply_patch(obj, [{'add': '/baz', 'value': 'qux'}])
|
||||||
|
|||||||
Reference in New Issue
Block a user