Gathering detailed insights and metrics for fast-json-patch
Gathering detailed insights and metrics for fast-json-patch
Gathering detailed insights and metrics for fast-json-patch
Gathering detailed insights and metrics for fast-json-patch
exframe-json-diff
This module is an extension of the `fast-json-patch` library, providing additional functionality to generate "diffs" (patch documents) with old value differences.
fast-diff
Fast Javascript text diff
json-joy
Collection of libraries for building collaborative editing apps.
language-subtag-registry
Full BCP 47 language subtag data from the official IANA repository, in JSON format with multiple indices.
Lean and mean Javascript implementation of the JSON-Patch standard (RFC 6902). Update JSON documents using delta patches.
npm install fast-json-patch
3.1.1
Published on 24 Mar 2022
Bug fixes and ES6 modules
Published on 13 Aug 2021
Use ES6 Modules
Published on 22 Aug 2019
Fix default import
Published on 09 Aug 2019
Generate invertible test operations
Published on 25 Jul 2019
Enhancements and bug fixes
Published on 01 Apr 2019
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
1,827 Stars
599 Commits
215 Forks
28 Watching
22 Branches
43 Contributors
Updated on 18 Nov 2024
Minified
Minified + Gzipped
JavaScript (86.59%)
TypeScript (12.28%)
HTML (0.54%)
CSS (0.44%)
Shell (0.15%)
Cumulative downloads
Total Downloads
Last day
-2.8%
609,303
Compared to previous day
Last week
1.4%
3,257,876
Compared to previous week
Last month
14.2%
13,531,390
Compared to previous month
Last year
9.8%
151,634,750
Compared to previous year
A leaner and meaner implementation of JSON-Patch. Small footprint. High performance.
With JSON-Patch, you can:
Tested in Firefox, Chrome, Edge, Safari, IE11, Deno and Node.js
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.
Mark Nottingham has a nice blog about it.
Download as ZIP or install the current version using a package manager (and save it as a dependency):
1# NPM 2npm install fast-json-patch --save
Load the bundled distribution script:
1<script src="dist/fast-json-patch.min.js"></script>
In browsers that support ECMAScript modules, the below code uses this library as a module:
1<script type="module"> 2 import * as jsonpatch from 'fast-json-patch/index.mjs'; 3 import { applyOperation } from 'fast-json-patch/index.mjs'; 4</script>
In Node 12+ with --experimental-modules
flag, the below code uses this library as an ECMAScript module:
1import * as jsonpatch from 'fast-json-patch/index.mjs'; 2import { applyOperation } from 'fast-json-patch/index.mjs';
In Webpack (and most surely other bundlers based on Babel), the below code uses this library as an ECMAScript module:
1import * as jsonpatch from 'fast-json-patch'; 2import { applyOperation } from 'fast-json-patch';
In standard Node, the below code uses this library as a CommonJS module:
1const { applyOperation } = require('fast-json-patch'); 2const applyOperation = require('fast-json-patch').applyOperation;
Directories used in this package:
dist/
- contains ES5 files for a Web browsercommonjs/
- contains CommonJS module and typingsmodule/
- contains ECMAScript module and typingssrc/
- contains TypeScript source filesfunction applyPatch<T>(document: T, patch: Operation[], validateOperation?: boolean | Validator<T>, mutateDocument: boolean = true, banPrototypeModifications: boolean = true): PatchResult<T>
Applies patch
array on obj
.
document
The document to patchpatch
a JSON-Patch array of operations to applyvalidateOperation
Boolean for whether to validate each operation with our default validator, or to pass a validator callbackmutateDocument
Whether to mutate the original document or clone it before applyingbanPrototypeModifications
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 testremove
, replace
and move
- original object that has been removedadd
(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.
See Validation notes.
Example:
1var document = { firstName: "Albert", contactDetails: { phoneNumbers: [] } }; 2var patch = [ 3 { op: "replace", path: "/firstName", value: "Joachim" }, 4 { op: "add", path: "/lastName", value: "Wester" }, 5 { op: "add", path: "/contactDetails/phoneNumbers/0", value: { number: "555-123" } } 6]; 7document = jsonpatch.applyPatch(document, patch).newDocument; 8// document == { firstName: "Joachim", lastName: "Wester", contactDetails: { phoneNumbers: [{number:"555-123"}] } };
function applyOperation<T>(document: T, operation: Operation, validateOperation: boolean | Validator<T> = false, mutateDocument: boolean = true, banPrototypeModifications: boolean = true, index: number = 0): OperationResult<T>
Applies single operation object operation
on document
.
document
The document to patchoperation
The operation to applyvalidateOperation
Whether to validate the operation, or to pass a validator callbackmutateDocument
Whether to mutate the original document or clone it before applyingbanPrototypeModifications
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.
See Validation notes.
Example:
1var document = { firstName: "Albert", contactDetails: { phoneNumbers: [] } }; 2var operation = { op: "replace", path: "/firstName", value: "Joachim" }; 3document = jsonpatch.applyOperation(document, operation).newDocument; 4// document == { firstName: "Joachim", contactDetails: { phoneNumbers: [] }}
jsonpatch.applyReducer<T>(document: T, operation: Operation, index: number): T
Ideal for patch.reduce(jsonpatch.applyReducer, document)
.
Applies single operation object operation
on document
.
Returns the a modified document.
Note: It throws TEST_OPERATION_FAILED
error if test
operation fails.
Example:
1var document = { firstName: "Albert", contactDetails: { phoneNumbers: [ ] } }; 2var patch = [ 3 { op:"replace", path: "/firstName", value: "Joachim" }, 4 { op:"add", path: "/lastName", value: "Wester" }, 5 { op:"add", path: "/contactDetails/phoneNumbers/0", value: { number: "555-123" } } 6]; 7var updatedDocument = patch.reduce(applyReducer, document); 8// updatedDocument == { firstName:"Joachim", lastName:"Wester", contactDetails:{ phoneNumbers[ {number:"555-123"} ] } };
jsonpatch.deepClone(value: any): any
Returns deeply cloned value.
jsonpatch.escapePathComponent(path: string): string
Returns the escaped path.
jsonpatch.unescapePathComponent(path: string): string
Returns the unescaped path.
jsonpatch.getValueByPointer(document: object, pointer: string)
Retrieves a value from a JSON document by a JSON pointer.
Returns the value.
jsonpatch.observe(document: any, callback?: Function): Observer
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.
Returns observer
.
jsonpatch.generate(document: any, observer: Observer, invertible = false): Operation[]
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).
Example:
1var document = { firstName: "Joachim", lastName: "Wester", contactDetails: { phoneNumbers: [ { number:"555-123" }] } }; 2var observer = jsonpatch.observe(document); 3document.firstName = "Albert"; 4document.contactDetails.phoneNumbers[0].number = "123"; 5document.contactDetails.phoneNumbers.push({ number:"456" }); 6var patch = jsonpatch.generate(observer); 7// patch == [ 8// { op: "replace", path: "/firstName", value: "Albert"}, 9// { op: "replace", path: "/contactDetails/phoneNumbers/0/number", value: "123" }, 10// { op: "add", path: "/contactDetails/phoneNumbers/1", value: {number:"456"}} 11// ];
Example of generating patches with test operations for values in the first object:
1var document = { firstName: "Joachim", lastName: "Wester", contactDetails: { phoneNumbers: [ { number:"555-123" }] } }; 2var observer = jsonpatch.observe(document); 3document.firstName = "Albert"; 4document.contactDetails.phoneNumbers[0].number = "123"; 5document.contactDetails.phoneNumbers.push({ number:"456" }); 6var patch = jsonpatch.generate(observer, true); 7// patch == [ 8// { op: "test", path: "/firstName", value: "Joachim"}, 9// { op: "replace", path: "/firstName", value: "Albert"}, 10// { op: "test", path: "/contactDetails/phoneNumbers/0/number", value: "555-123" }, 11// { op: "replace", path: "/contactDetails/phoneNumbers/0/number", value: "123" }, 12// { op: "add", path: "/contactDetails/phoneNumbers/1", value: {number:"456"}} 13// ];
jsonpatch.unobserve(document, observer)
1jsonpatch.unobserve(document: any, observer: Observer): void 2 3type JsonableObj = { [key:string]: Jsonable }; 4type JsonableArr = Jsonable[]; 5type Jsonable = JsonableArr | JsonableObj | string | number | boolean | null;
Destroys the observer set up on document
.
Any remaining changes are delivered synchronously (as in jsonpatch.generate
). Note: this is different that ES6/7 Object.unobserve
, which delivers remaining changes asynchronously.
jsonpatch.compare(document1, document2, invertible)
1jsonpatch.compare(document1: Jsonable, document2: Jsonable, invertible = false): Operation[] 2 3type JsonableObj = { [key:string]: Jsonable }; 4type JsonableArr = Jsonable[]; 5type Jsonable = JsonableArr | JsonableObj | string | number | boolean | null;
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).
Example:
1var documentA = {user: {firstName: "Albert", lastName: "Einstein"}}; 2var documentB = {user: {firstName: "Albert", lastName: "Collins"}}; 3var diff = jsonpatch.compare(documentA, documentB); 4//diff == [{op: "replace", path: "/user/lastName", value: "Collins"}]
Example of comparing two object trees with test operations for values in the first object:
1var documentA = {user: {firstName: "Albert", lastName: "Einstein"}}; 2var documentB = {user: {firstName: "Albert", lastName: "Collins"}}; 3var diff = jsonpatch.compare(documentA, documentB, true); 4//diff == [ 5// {op: "test", path: "/user/lastName", value: "Einstein"}, 6// {op: "replace", path: "/user/lastName", value: "Collins"} 7// ];
jsonpatch.validate(patch: Operation[], document?: any, validator?: Function): JsonPatchError
See Validation notes
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 codemessage
String - long human readable error messageindex
Number - index of the operation in the sequenceoperation
Object - reference to the operationtree
Object - reference to the treePossible 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:
1var obj = {user: {firstName: "Albert"}}; 2var patches = [{op: "replace", path: "/user/firstName", value: "Albert"}, {op: "replace", path: "/user/lastName", value: "Einstein"}]; 3var errors = jsonpatch.validate(patches, obj); 4if (errors.length == 0) { 5 //there are no errors! 6} 7else { 8 for (var i=0; i < errors.length; i++) { 9 if (!errors[i]) { 10 console.log("Valid patch at index", i, patches[i]); 11 } 12 else { 13 console.error("Invalid patch at index", i, errors[i], patches[i]); 14 } 15 } 16}
OperationResult
TypeFunctions applyPatch
and applyOperation
both return OperationResult
object. This object is:
1{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.Functions applyPatch
, applyOperation
, and validate
accept a validate
/ validator
parameter:
validateOperation
parameter is set to false
, validation will not occur.true
, the patch is extensively validated before applying using jsonpatch's default validation.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.index
operation
's index in the patch array (if application).tree
The object that is supposed to be patched.existingPath
the path operation
points to.move
OperationWhen the target of the move operation already exists, it is cached, deep cloned and returned as removed
in OperationResult
.
undefined
s (JS to JSON projection)As undefined
type does not exist in JSON, it's also not a valid value of JSON Patch operation. Therefore jsonpatch
will not generate JSON Patches that sets anything to undefined
.
Whenever a value is set to undefined
in JS, JSON-Patch methods generate
and compare
will treat it similarly to how JavaScript method JSON.stringify
(MDN) treats them:
If
undefined
(...) is encountered during conversion it is either omitted (when it is found in an object) or censored tonull
(when it is found in an array).
See the ECMAScript spec for details.
To see the list of recent changes, see Releases.
4 KB minified and gzipped (12 KB minified)
add
benchmarkreplace
benchmarkTested on 29.08.2018. Compared libraries:
We aim the tests to be fair. Our library puts performance as the #1 priority, while other libraries can have different priorities. If you'd like to update the benchmarks or add a library, please fork the perf.zone benchmarks linked above and open an issue to include new results.
MIT
The latest stable version of the package.
Stable Version
1
7.3/10
Summary
Starcounter-Jack JSON-Patch Prototype Pollution vulnerability
Affected Versions
< 3.1.1
Patched Versions
3.1.1
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 2/15 approved changesets -- score normalized to 1
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
37 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More