JSON Object Diffing and Patching

2.0.0 · abandoned · verified Sun Apr 19

diff-json is a JavaScript library (version 2.0.0, last updated in 2017) designed to generate structural differences between JavaScript objects, and subsequently apply or revert those changes. Inspired by `eugeneware/changeset`, it offers `diff`, `applyChanges`, and `revertChanges` functionalities. A key differentiator is its ability to handle array diffing by specifying a primary key for embedded objects, ensuring accurate comparison beyond simple positional changes. However, due to its age and lack of maintenance since 2017, it does not support modern JavaScript features like ES Modules or TypeScript and has an uncertain future regarding bug fixes or security updates. Alternative modern libraries like `json-diff-ts` offer similar functionality with current ecosystem support.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to generate a diff between two JSON objects, apply those changes to an object, and then revert the changes to restore a previous state. It highlights the use of the `embededKey` option for intelligent array diffing.

const changesets = require('diff-json');

const oldObj = {
  name: 'joe',
  age: 55,
  coins: [2, 5],
  children: [
    {name: 'kid1', age: 1},
    {name: 'kid2', age: 2}
  ]
};

const newObj = {
  name: 'smith',
  coins: [2, 5, 1],
  children: [
    {name: 'kid3', age: 3},
    {name: 'kid1', age: 0},
    {name: 'kid2', age: 2}
  ]
};

// Generate a diff, specifying 'name' as the primary key for children array elements
const diffs = changesets.diff(oldObj, newObj, {children: 'name'});

console.log('Generated Diffs:', JSON.stringify(diffs, null, 2));
/*
Example Output (truncated):
[
  { "type": "update", "key": "name", "value": "smith", "oldValue": "joe" },
  { "type": "update", "key": "coins", "embededKey": "$index", "changes": [ { "type": "add", "key": "2", "value": 1 } ] },
  { "type": "update", "key": "children", "embededKey": "name", "changes": [ { "type": "update", "key": "kid1", "changes": [ { "type": "update", "key": "age", "value": 0, "oldValue": 1 } ] }, { "type": "add", "key": "kid3", "value": { "name": "kid3", "age": 3 } } ] },
  { "type": "remove", "key": "age", "value": 55 }
]
*/

// Apply changes to a base object
const targetObj = JSON.parse(JSON.stringify(oldObj)); // Deep clone to avoid mutating oldObj
changesets.applyChanges(targetObj, diffs);

console.log('\nObject after applying changes:', JSON.stringify(targetObj, null, 2));

// Revert changes on a modified object to get back to the original state
const revertableObj = JSON.parse(JSON.stringify(newObj)); // Start with newObj to revert to oldObj state
const revertedDiffs = changesets.revertChanges(diffs); // Revert the diffs themselves
changesets.applyChanges(revertableObj, revertedDiffs);

console.log('\nObject after reverting changes:', JSON.stringify(revertableObj, null, 2));

view raw JSON →