jsonpatch-js
Library to apply JSON Patches in JavaScript
- JSON Patch - http://tools.ietf.org/html/rfc6902
- JSON Pointer - http://tools.ietf.org/html/rfc6901
jsonpatch-js works as in the browser as a script, as a Node module and as an AMD module.
Install
Bower
bower install json-patch
NPM
npm install json-patch
Note: at this time, all operations are applied in-place.
Methods
jsonpatch.apply(document, patch)
Applies a patch to the document
jsonpatch.compile(patch)
Compiles a patch and returns a function that takes a document to apply the patch to.
Patch Operations
Add
Patch syntax: {op: 'add', path: <path>, value: <value>}
// Add property, result: {foo: 'bar'}jsonpatch; // Add array element, result: {foo: [1, 2, 3]}jsonpatch; // Complex, result: {foo: [{bar: 'baz'}]}jsonpatch;
Remove
Patch syntax: {op: 'remove', path: <path>}
// Remove property, result: {}jsonpatch; // Remove array element, result: {foo: [1, 3]}jsonpatch; // Complex, result: {foo: [{}]}jsonpatch;
Replace
Patch syntax: {op: 'replace', path: <path>, value: <value>}
// Replace property, result: {foo: 1}jsonpatch; // Replace array element, result: {foo: [1, 4, 3]}jsonpatch; // Complex, result: {foo: [{bar: 1}]}jsonpatch;
Move
Patch syntax: {op: 'move', from: <path>, path: <path>}
// Move property, result {bar: [1, 2, 3]}jsonpatch;
Copy
Patch syntax: {op: 'copy', from: <path>, path: <path>}
// Copy property, result {foo: [1, 2, 3], bar: 2}jsonpatch;
Test
Patch syntax: {op: 'test', path: <path>, value: <value>}
// Test equality of property to value, result: truejsonpatch
Changed in 0.5.0
The return value is no longer a boolean, but now the the document itself which adheres correctly to the specification. It the test fails, a PatchTestFailed
error will be thrown.
Error Types
JSONPatchError
Base error type which all patch errors extend from.
InvalidPointerError
Thrown when the pointer is invalid.
InvalidPatchError
Thrown when the patch itself has an invalid syntax.
PatchConflictError
Thrown when there is a conflic with applying the patch to the document.
PatchTestFailed
Thrown when a test operation is applied and fails.