JSON Patch RFC 6902 implementation for JavaScript.
See jsonpatch.com for more information about JSON Patch.
JSON8 Patch passes the entire json-patch-tests suite; see Tests
npm install json8-patch
var ooPatch = require('json8-patch');or
<script src="node_modules/json8-patch/JSON8Patch.js"></script>var ooPatch = window.JSON8PatchFor performance concerns JSON8 Patch mutates documents; if you want it to work on its own shallow copy of your document use:
var oo = require('json8')
doc = oo.clone(doc)See clone.
doc = ooPatch.apply(doc, [
{ "op": "add", "path": "/tags/0", "value": "family" },
{ "op": "remove", "path": "/height" },
{ "op": "replace", "path": "/age", "value": "26" },
{ "op": "move", "from": "/address/city", "path": "/address/country" },
{ "op": "copy", "from": "/starred", "to": "bookmarked" },
{ "op": "test", "path": "/starred", "value": true }
]);ooPatch.apply returns a document because the JSON Patch specification states that an operation can replace the original document.
ooPatch.apply is atomic, if any operation fails, the document will be restored to its original state and an error will be thrown.
Alias for apply method.
If the patch or apply method is called with a third argument {reversible: true} it will return an array of the form [doc, revert].
The revert object can be used to revert a patch on a document.
// apply the patch with the reversible option
var patchResult = ooPatch.apply(doc, patch, {reversible: true});
doc = patchResult[0];
// revert the patch
doc = ooPatch.revert(doc, patchResult[1]);
// doc is strictly identical to the originaadd, copy, replace, move, remove, test operations return an array of the form [document, previous, idx]
The first argument is the patched document.
The second argument is the previous value at the specified destination if any, undefined otherwise.
The third argument is used internaly and can be ignored. It is the index of the new element. For add operation only using the JSON Pointer '-' token to push an item at the end of an array.
doc = ooPatch.add(doc, '/foo', 'foo')[0]doc = ooPatch.remove(doc, '/foo')[0];doc = ooPatch.replace(doc, '/foo', 'foo')[0];doc = ooPatch.move(doc, '/foo', '/bar')[0];doc = ooPatch.copy(doc, '/foo', '/bar')[0];doc = ooPatch.test(doc, '/foo', 'bar')[0];Those are not part of the standard and are only provided for convenience.
ooPatch.get(doc, '/foo');
// returns value at /fooooPatch.has(doc, '/foo');
// returns true if there is a value at /foogit submodule update --init --recursive
npm install -g mocha babel browserify
npm test
See CONTRIBUTING.md