What is jsondiffpatch?
The jsondiffpatch npm package is a tool for computing the difference between two JSON objects and applying those differences to other JSON objects. It is useful for tasks such as data synchronization, version control, and change tracking in JSON data structures.
What are jsondiffpatch's main functionalities?
Diff
This feature computes the difference between two JSON objects. In this example, the difference between the 'left' and 'right' objects is calculated, resulting in a delta that shows the change in the 'age' property.
const jsondiffpatch = require('jsondiffpatch');
const left = { name: 'John', age: 30 };
const right = { name: 'John', age: 31 };
const delta = jsondiffpatch.diff(left, right);
console.log(delta);
Patch
This feature applies a delta (difference) to a JSON object to produce a new JSON object. In this example, the delta is applied to the 'left' object, resulting in the 'right' object with the updated 'age' property.
const jsondiffpatch = require('jsondiffpatch');
const left = { name: 'John', age: 30 };
const delta = { age: [30, 31] };
const right = jsondiffpatch.patch(left, delta);
console.log(right);
Unpatch
This feature reverts a JSON object to its previous state by applying the inverse of a delta. In this example, the delta is used to revert the 'right' object back to the 'left' object.
const jsondiffpatch = require('jsondiffpatch');
const right = { name: 'John', age: 31 };
const delta = { age: [30, 31] };
const left = jsondiffpatch.unpatch(right, delta);
console.log(left);
Reverse
This feature computes the inverse of a delta, which can be used to revert changes. In this example, the inverse of the delta is calculated, which can then be used to revert the changes made by the original delta.
const jsondiffpatch = require('jsondiffpatch');
const delta = { age: [30, 31] };
const reverseDelta = jsondiffpatch.reverse(delta);
console.log(reverseDelta);
Other packages similar to jsondiffpatch
deep-diff
The deep-diff package provides similar functionality for computing differences between JavaScript objects. It offers a more granular approach to detecting changes, including additions, deletions, and modifications. However, it does not provide built-in patching and unpatching capabilities like jsondiffpatch.
diff
The diff package is a general-purpose text and data comparison tool that can be used to compute differences between strings, arrays, and objects. While it is versatile and widely used, it lacks the specialized JSON diffing and patching features provided by jsondiffpatch.
fast-json-patch
The fast-json-patch package focuses on applying JSON Patch operations as defined by RFC 6902. It is optimized for performance and provides a simple API for applying and validating JSON patches. However, it does not compute differences between JSON objects, which is a key feature of jsondiffpatch.
jsondiffpatch
Diff & patch JavaScript objects
- min+gzipped ~ 16KB
- browser and server (
/dist
folder with bundles for UMD, commonjs, or ES modules) - (optionally) uses google-diff-match-patch for long text diffs (diff at character level)
- smart array diffing using LCS, IMPORTANT NOTE: to match objects inside an array you must provide an
objectHash
function (this is how objects are matched, otherwise a dumb match by position is used). For more details, check Array diff documentation - reverse a delta
- unpatch (eg. revert object to its original state using a delta)
- simplistic, pure JSON, low footprint delta format
- multiple output formatters:
- html (check it at the Live Demo)
- annotated json (html), makes the JSON delta format self-explained
- console (colored), try running
./node_modules/.bin/jsondiffpatch left.json right.json
- JSON Patch format RFC 6902 support
- write your own! check Formatters documentation
- BONUS:
jsondiffpatch.clone(obj)
(deep clone)
Supported platforms
- Any modern browser and IE8+
And you can test your current browser visiting the test page.
- Node.js v8+
Usage
var country = {
name: "Argentina",
capital: "Buenos Aires",
independence: new Date(1816, 6, 9),
unasur: true
};
var country2 = JSON.parse(JSON.stringify(country), jsondiffpatch.dateReviver);
country2.name = "Republica Argentina";
country2.population = 41324992;
delete country2.capital;
var delta = jsondiffpatch.diff(country, country2);
assertSame(delta, {
"name":["Argentina","Republica Argentina"],
"population":["41324992"],
"capital":["Buenos Aires", 0, 0]
});
jsondiffpatch.patch(country, delta);
var reverseDelta = jsondiffpatch.reverse(delta);
var delta2 = jsondiffpatch.diff(country, country2);
assert(delta2 === undefined)
Array diffing:
var country = {
name: "Argentina",
cities: [
{
name: 'Buenos Aires',
population: 13028000,
},
{
name: 'Cordoba',
population: 1430023,
},
{
name: 'Rosario',
population: 1136286,
},
{
name: 'Mendoza',
population: 901126,
},
{
name: 'San Miguel de Tucuman',
population: 800000,
}
]
};
var country2 = JSON.parse(JSON.stringify(country));
country.cities.splice(1, 1);
country.cities.splice(4, 0, {
name: 'La Plata'
});
var rosario = country.cities.splice(1, 1)[0];
rosario.population += 1234;
country.cities.push(rosario);
var diffpatcher = jsondiffpatch.create({
objectHash: function(obj) {
return obj.name;
}
});
var delta = diffpatcher.diff(country, country2);
assertSame(delta, {
"cities": {
"_t": "a",
"1": [
{
"name": "Cordoba",
"population": 1430023
}]
,
"2": {
"population": [
1137520,
1136286
]
},
"_3": [
{
"name": "La Plata"
}, 0, 0],
"_4": [
'', 2, 3]
}
});
For more example cases (nested objects or arrays, long text diffs) check test/examples/
If you want to understand deltas, see delta format documentation
Installing
NPM
This works for node, or in browsers if you already do bundling on your app
npm install jsondiffpatch
var jsondiffpatch = require('jsondiffpatch').create(options);
browser
In a browser, you could load directly a bundle in /dist
, eg. /dist/jsondiffpatch.umd.js
.
Options
var jsondiffpatch = require('jsondiffpatch').create({
objectHash: function(obj) {
return obj._id || obj.id;
},
arrays: {
detectMove: true,
includeValueOnMove: false
},
textDiff: {
minLength: 60
},
propertyFilter: function(name, context) {
return name.slice(0, 1) !== '$';
},
cloneDiffValues: false
});
Visual Diff
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src="https://cdn.jsdelivr.net/npm/jsondiffpatch/dist/jsondiffpatch.umd.min.js"></script>
<link rel="stylesheet" href="./style.css" type="text/css" />
<link rel="stylesheet" href="../formatters-styles/html.css" type="text/css" />
<link rel="stylesheet" href="../formatters-styles/annotated.css" type="text/css" />
</head>
<body>
<div id="visual"></div>
<hr/>
<div id="annotated"></div>
<script>
var left = { a: 3, b: 4 };
var right = { a: 5, c: 9 };
var delta = jsondiffpatch.diff(left, right);
document.getElementById('visual').innerHTML = jsondiffpatch.formatters.html.format(delta, left);
document.getElementById('annotated').innerHTML = jsondiffpatch.formatters.annotated.format(delta, left);
</script>
</body>
</html>
To see formatters in action check the Live Demo.
For more details check Formatters documentation
Console
./node_modules/.bin/jsondiffpatch ./left.json ./right.json
npm install -g jsondiffpatch
jsondiffpatch ./demo/left.json ./demo/right.json
Plugins
diff()
, patch()
and reverse()
functions are implemented using Pipes & Filters pattern, making it extremely customizable by adding or replacing filters on a pipe.
Check Plugins documentation for details.