diff options
author | Christian Lyder Jacobsen <christian@yocuda.com> | 2020-03-06 11:41:38 +0100 |
---|---|---|
committer | Christian Lyder Jacobsen <christian@yocuda.com> | 2020-03-06 12:07:24 +0100 |
commit | 0167d345ee9d7ef0f74b947ec3a7ea94def178be (patch) | |
tree | 34b4358b9b96ac73ca06c5d741bd7c344cb164a8 /jsonpatch.py | |
parent | e99d178396f69f8891a62e21434c2783b76146b2 (diff) | |
download | python-json-patch-0167d345ee9d7ef0f74b947ec3a7ea94def178be.tar.gz |
Subclassing can override json dumper and loader
Additionally:
* from_string gets a loads parameter
* to_string gets a dumps_parameter
* documentation added
* added more tests
Diffstat (limited to 'jsonpatch.py')
-rw-r--r-- | jsonpatch.py | 22 |
1 files changed, 15 insertions, 7 deletions
diff --git a/jsonpatch.py b/jsonpatch.py index ebaa8e3..ce8a89f 100644 --- a/jsonpatch.py +++ b/jsonpatch.py @@ -165,6 +165,9 @@ def make_patch(src, dst): class JsonPatch(object): + json_dumper = staticmethod(json.dumps) + json_loader = staticmethod(_jsonloads) + """A JSON Patch is a list of Patch Operations. >>> patch = JsonPatch([ @@ -246,19 +249,23 @@ class JsonPatch(object): return not(self == other) @classmethod - def from_string(cls, patch_str): + def from_string(cls, patch_str, loads=None): """Creates JsonPatch instance from string source. :param patch_str: JSON patch as raw string. :type patch_str: str + :param loads: A function of one argument that loads a serialized + JSON string. + :type loads: function :return: :class:`JsonPatch` instance. """ - patch = _jsonloads(patch_str) + json_loader = loads or cls.json_loader + patch = json_loader(patch_str) return cls(patch) @classmethod - def from_diff(cls, src, dst, optimization=True, dumps=json.dumps): + def from_diff(cls, src, dst, optimization=True, dumps=None): """Creates JsonPatch instance based on comparing of two document objects. Json patch would be created for `src` argument against `dst` one. @@ -282,15 +289,16 @@ class JsonPatch(object): >>> new == dst True """ - - builder = DiffBuilder(dumps) + json_dumper = dumps or cls.json_dumper + builder = DiffBuilder(json_dumper) builder._compare_values('', None, src, dst) ops = list(builder.execute()) return cls(ops) - def to_string(self): + def to_string(self, dumps=None): """Returns patch set as JSON string.""" - return json.dumps(self.patch) + json_dumper = dumps or self.json_dumper + return json_dumper(self.patch) @property def _ops(self): |