JSON Patch and Pointer Implementation

0.7.0 · abandoned · verified Wed Apr 22

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.

Common errors

Warnings

Install

Imports

Quickstart

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);
  }
}

view raw JSON →