A leaner and meaner implementation of JSON-Patch. Small footprint. High performance.
With JSON-Patch, you can:
apply patches (arrays) and single operations on JS object
validate a sequence of patches
observe for changes and generate patches when a change is detected
compare two objects to obtain the difference
Tested in Firefox, Chrome, Edge, Safari, IE11, Deno and Node.js
Why you should use JSON-Patch
JSON-Patch (RFC6902) is a standard format that
allows you to update a JSON document by sending the changes rather than the whole document.
JSON Patch plays well with the HTTP PATCH verb (method) and REST style programming.
validateOperation Boolean for whether to validate each operation with our default validator, or to pass a validator callback
mutateDocument Whether to mutate the original document or clone it before applying
banPrototypeModifications Whether to ban modifications to __proto__, defaults to true.
An invalid patch results in throwing an error (see jsonpatch.validate for more information about the error object).
It modifies the document object and patch - it gets the values by reference.
If you would like to avoid touching your patch array values, clone them: jsonpatch.applyPatch(document, jsonpatch.deepClone(patch)).
Returns an array of OperationResult objects - one item for each item in patches, each item is an object {newDocument: any, test?: boolean, removed?: any}.
test - boolean result of the test
remove, replace and move - original object that has been removed
add (only when adding to an array) - index at which item has been inserted (useful when using - alias)
** Note: It throws TEST_OPERATION_FAILED error if test operation fails. **
** Note II: the returned array has newDocument property that you can use as the final state of the patched document **.
** Note III: By default, when banPrototypeModifications is true, this method throws a TypeError when you attempt to modify an object's prototype.
Applies single operation object operation on document.
document The document to patch
operation The operation to apply
validateOperation Whether to validate the operation, or to pass a validator callback
mutateDocument Whether to mutate the original document or clone it before applying
banPrototypeModifications Whether to ban modifications to __proto__, defaults to true.
index The index of the operation in your patch array. Useful for better error reporting when that operation fails to apply.
It modifies the document object and operation - it gets the values by reference.
If you would like to avoid touching your values, clone them: jsonpatch.applyOperation(document, jsonpatch.deepClone(operation)).
Returns an OperationResult object {newDocument: any, test?: boolean, removed?: any}.
** Note: It throws TEST_OPERATION_FAILED error if test operation fails. **
** Note II: By default, when banPrototypeModifications is true, this method throws a TypeError when you attempt to modify an object's prototype.
Sets up an deep observer on document that listens for changes in object tree. When changes are detected, the optional
callback is called with the generated patches array as the parameter.
If there are pending changes in obj, returns them synchronously. If a callback was defined in observe
method, it will be triggered synchronously as well. If invertible is true, then each change will be preceded by a test operation of the value before the change.
If there are no pending changes in obj, returns an empty array (length 0).
Any remaining changes are delivered synchronously (as in jsonpatch.generate). Note: this is different that ES6/7 Object.unobserve, which delivers remaining changes asynchronously.
Compares object trees document1 and document2 and returns the difference relative to document1 as a patches array. If invertible is true, then each change will be preceded by a test operation of the value in document1.
If there are no differences, returns an empty array (length 0).
Validates a sequence of operations. If document parameter is provided, the sequence is additionally validated against the object tree.
If there are no errors, returns undefined. If there is an errors, returns a JsonPatchError object with the following properties:
name String - short error code
message String - long human readable error message
index Number - index of the operation in the sequence
operation Object - reference to the operation
tree Object - reference to the tree
Possible errors:
Error name
Error message
SEQUENCE_NOT_AN_ARRAY
Patch sequence must be an array
OPERATION_NOT_AN_OBJECT
Operation is not an object
OPERATION_OP_INVALID
Operation op property is not one of operations defined in RFC-6902
OPERATION_PATH_INVALID
Operation path property is not a valid string
OPERATION_FROM_REQUIRED
Operation from property is not present (applicable in move and copy operations)
OPERATION_VALUE_REQUIRED
Operation value property is not present, or undefined (applicable in add, replace and test operations)
OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED
Operation value property object has at least one undefined value (applicable in add, replace and test operations)
OPERATION_PATH_CANNOT_ADD
Cannot perform an add operation at the desired path
OPERATION_PATH_UNRESOLVABLE
Cannot perform the operation at a path that does not exist
OPERATION_FROM_UNRESOLVABLE
Cannot perform the operation from a path that does not exist
OPERATION_PATH_ILLEGAL_ARRAY_INDEX
Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index
OPERATION_VALUE_OUT_OF_BOUNDS
The specified index MUST NOT be greater than the number of elements in the array
TEST_OPERATION_FAILED
When operation is test and the test fails, applies to applyReducer.
Example:
varobj={user: {firstName: "Albert"}};varpatches=[{op: "replace",path: "/user/firstName",value: "Albert"},{op: "replace",path: "/user/lastName",value: "Einstein"}];varerrors=jsonpatch.validate(patches,obj);if(errors.length==0){//there are no errors!}else{for(vari=0;i<errors.length;i++){if(!errors[i]){console.log("Valid patch at index",i,patches[i]);}else{console.error("Invalid patch at index",i,errors[i],patches[i]);}}}
OperationResult Type
Functions applyPatch and applyOperation both return OperationResult object. This object is:
{newDocument: any,test?: boolean,removed?: any}
Where:
newDocument: the new state of the document after the patch/operation is applied.
test: if the operation was a test operation. This will be its result.
removed: contains the removed, moved, or replaced values from the document after a remove, move or replace operation.
Validation Notes
Functions applyPatch, applyOperation, and validate accept a validate/ validator parameter:
If the validateOperation parameter is set to false, validation will not occur.
If set to true, the patch is extensively validated before applying using jsonpatch's default validation.
If set to a function callback, the patch is validated using that function.
If you pass a validator, it will be called with four parameters for each operation, function(operation, index, tree, existingPath) and it is expected to throw JsonPatchError when your conditions are not met.
operation The operation it self.
indexoperation's index in the patch array (if application).
tree The object that is supposed to be patched.
existingPath the path operation points to.
Overwriting and move Operation
When the target of the move operation already exists, it is cached, deep cloned and returned as removed in OperationResult.
请发表评论