Registry / serialization / json-patch

json-patch

JSON →
library0.1jsnpmunverified

This library provides a JavaScript implementation of the JSON Patch (RFC 6902) and JSON Pointer (RFC 6901) specifications. It allows for applying changes to JSON documents, including operations like add, remove, replace, move, copy, and test. The current stable version is 0.7.0. A key characteristic is that all patch operations are applied *in-place*, directly modifying the input document, which can lead to significant side effects. The package supports usage in browsers, Node.js environments via CommonJS, and AMD modules. Given its version and the age of its last known development activity (last commit over 10 years ago on its GitHub repository), the package is considered unmaintained and has not seen updates for several years, making it unsuitable for new projects requiring active support or modern features. It adheres to the RFC standards but lacks modern JavaScript conveniences or TypeScript support.

npm install json-patch
INSTALL
IMPORT
SIG · JSON-PATCH
J
json-patch
serializationjavascriptv0.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

jsonpatch
import jsonpatch from 'json-patch'; // Or for CommonJS: const jsonpatch = require('json-patch');
import { apply } from 'json-patch'; // The library exports a single default object, not named functions. const { apply } = require('json-patch'); // Destructuring will not work as it's not a direct named export.
The library primarily exports a single 'jsonpatch' object. For ESM, use a default import. For CommonJS, use `require()` to import the entire object.
jsonpatch.apply
import jsonpatch from 'json-patch'; const document = {}; const patch = []; jsonpatch.apply(document, patch);
import { apply } from 'json-patch'; // 'apply' is a method on the default export, not a top-level named export.
The `apply` function is a method available on the main `jsonpatch` object after importing the library.
jsonpatch.JSONPatchError
import jsonpatch from 'json-patch'; try { /* ... */ } catch (e) { if (e instanceof jsonpatch.JSONPatchError) { /* handle */ } }
import { JSONPatchError } from 'json-patch'; // Error classes are properties of the main 'jsonpatch' object, not named exports.
Custom error constructors like `JSONPatchError`, `PatchTestFailed`, etc., are exposed as properties of the main `jsonpatch` object, not as direct named exports.

Demonstrates applying various JSON Patch operations (replace, add, remove, copy, test) to an object and handling potential errors, specifically highlighting the library's in-place modification behavior.

import jsonpatch from 'json-patch'; // Example document to be patched const originalDocument = { id: 1, user: { name: 'Alice', age: 30 }, tags: ['admin', 'editor'], settings: { theme: 'dark' } }; // A series of JSON Patch operations const patch = [ { op: 'replace', path: '/user/age', value: 31 }, { op: 'add', path: '/tags/0', value: 'premium' }, { op: 'remove', path: '/settings/theme' }, { op: 'copy', from: '/user/name', path: '/creator' }, { op: 'test', path: '/user/name', value: 'Alice' } // This will pass ]; console.log('Original Document:', JSON.stringify(originalDocument, null, 2)); try { // WARNING: jsonpatch.apply modifies the document in-place. // If you need to preserve the original, clone it first. const patchedDocument = jsonpatch.apply(originalDocument, patch); console.log('\nPatched Document (in-place modified):', JSON.stringify(patchedDocument, null, 2)); console.log('Original Document after patch (also modified):', JSON.stringify(originalDocument, null, 2)); // Example of a failing test operation const failingPatch = [{ op: 'test', path: '/user/age', value: 25 }]; console.log('\nAttempting a failing test operation...'); jsonpatch.apply(originalDocument, failingPatch); // This will throw } catch (e) { if (e instanceof jsonpatch.PatchTestFailed) { console.error('\nCaught a PatchTestFailed error:', e.message); } else if (e instanceof jsonpatch.InvalidPatchError) { console.error('\nCaught an InvalidPatchError:', e.message); } else if (e instanceof jsonpatch.InvalidPointerError) { console.error('\nCaught an InvalidPointerError:', e.message); } else { console.error('\nAn unexpected error occurred:', e.message); } }
Debug
Known issues
gotchaAll patch operations (add, remove, replace, move, copy, test) are applied directly 'in-place', mutating the original document object provided as the first argument. This behavior can lead to unexpected side effects if not explicitly handled by cloning the document beforehand.
fix
To prevent unintended mutations, always clone your document before applying the patch: `const clonedDocument = JSON.parse(JSON.stringify(originalDocument)); jsonpatch.apply(clonedDocument, patch);`
affects: >=0.1.0
breakingThe `test` operation's return value changed significantly in version 0.5.0. Prior to 0.5.0, it returned a boolean (true/false) indicating success or failure. Since 0.5.0, it returns the document itself on success and throws a `PatchTestFailed` error on failure, aligning with the JSON Patch specification.
fix
Update your error handling logic to catch `jsonpatch.PatchTestFailed` instead of checking a boolean return value. Example: `try { jsonpatch.apply(doc, [{op: 'test', path: '/foo', value: 'bar'}]) } catch (e) { if (e instanceof jsonpatch.PatchTestFailed) { /* handle failure */ } }`
affects: >=0.5.0
breakingThis package is considered abandoned and unmaintained. Its last significant commit on GitHub was over 10 years ago. It does not receive security updates, bug fixes, or new feature development, making it unsuitable for new projects or production environments that require ongoing support.
fix
It is strongly recommended to migrate to actively maintained JSON Patch libraries such as `fast-json-patch` or `json-patch-es6` for better support, performance, and modern JavaScript features.
affects: >=0.7.0
gotchaThe package does not ship with TypeScript type definitions, which is common for older JavaScript libraries. Developers using TypeScript will need to create their own declaration files (`.d.ts`) or use an external `@types/json-patch` package if one exists, though support for abandoned libraries is often limited.
fix
Manually declare types in a `.d.ts` file (e.g., `declare module 'json-patch' { ... }`) to provide type safety, or consider switching to a modern, actively maintained library with native TypeScript support.
affects: >=0.1.0
Errors
Common errors & fixes
Uncaught PatchTestFailed: Test operation failed
A `test` operation within the JSON patch found that the specified path did not contain the expected value, leading to a failure and halting the patch application.
fix
Ensure the `value` provided in the `test` operation precisely matches the actual value at the `path` in the document, or adjust the patch logic to reflect the expected state.
Uncaught InvalidPatchError: Expected an object, got...
One of the patch operations provided (e.g., add, remove, replace, etc.) has an invalid or malformed structure, or is missing required fields such as 'op', 'path', 'from', or 'value' as defined by RFC 6902.
fix
Carefully verify that each object in your patch array strictly adheres to the JSON Patch RFC 6902 specification for the respective operation type.
Uncaught InvalidPointerError: Invalid pointer: ...
A JSON Pointer path (e.g., `/foo/bar`) used in a patch operation is syntactically incorrect, malformed, or references a non-existent or invalid segment within the document structure (e.g., attempting to access `/foo/bar` when `foo` is not an object).
fix
Review the `path` or `from` fields in your patch operations to ensure they are valid JSON Pointers and accurately correspond to the structure of your target document.
TypeError: jsonpatch.apply is not a function
This error commonly occurs when attempting to destructure `apply` as a named export in ESM or CommonJS, or when the `jsonpatch` object itself is not correctly imported (e.g., it might be undefined or an empty object). The library exports a single object, not individual functions.
fix
For CommonJS, use `const jsonpatch = require('json-patch');`. For ESM, use `import jsonpatch from 'json-patch';`. Always access functions via the `jsonpatch` object: `jsonpatch.apply(...)`.
Upgrade
Version history
0.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
4 hits · last 30 days
node
4
Resources
json-patch — npm install json-patch · libregistry