Skip to content

Commit be9be6d

Browse files
committed
Let apply_patch to handle patch as JSON-encoded string.
1 parent e90dba0 commit be9be6d

2 files changed

Lines changed: 16 additions & 2 deletions

File tree

jsonpatch.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@
4747
else:
4848
import json
4949

50+
if sys.version_info >= (3, 0):
51+
basestring = (bytes, str)
52+
5053

5154
class JsonPatchException(Exception):
5255
"""Base Json Patch exception"""
@@ -67,7 +70,7 @@ def apply_patch(doc, patch, in_place=False):
6770
:param doc: Document object.
6871
:type doc: dict
6972
70-
:param patch: JSON patch as list of dicts.
73+
:param patch: JSON patch as list of dicts or raw JSON-encoded string.
7174
:type patch: list
7275
7376
:param in_place: While :const:`True` patch will modify target document.
@@ -89,7 +92,10 @@ def apply_patch(doc, patch, in_place=False):
8992
True
9093
"""
9194

92-
patch = JsonPatch(patch)
95+
if isinstance(patch, basestring):
96+
patch = JsonPatch.from_string(patch)
97+
else:
98+
patch = JsonPatch(patch)
9399
return patch.apply(doc, in_place)
94100

95101
def make_patch(src, dst):

tests.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,14 @@
88

99
class ApplyPatchTestCase(unittest.TestCase):
1010

11+
def test_apply_patch_from_string(self):
12+
obj = {'foo': 'bar'}
13+
patch = '[{"add": "/baz", "value": "qux"}]'
14+
res = jsonpatch.apply_patch(obj, patch)
15+
self.assertTrue(obj is not res)
16+
self.assertTrue('baz' in res)
17+
self.assertEqual(res['baz'], 'qux')
18+
1119
def test_apply_patch_to_copy(self):
1220
obj = {'foo': 'bar'}
1321
res = jsonpatch.apply_patch(obj, [{'add': '/baz', 'value': 'qux'}])

0 commit comments

Comments
 (0)