Top Related Projects
Javascript utility for calculating deep difference, capturing changes, and applying changes across objects; for nodejs and the browser.
A fast, zero dependency object and array comparison library. Significantly faster than most other deep comparison libraries and has full TypeScript support.
Quick Overview
jsondiffpatch is a JavaScript library for diffing and patching JSON objects. It allows users to compare two JSON structures, generate a compact description of their differences, and apply those differences as patches to transform one object into another. This library is useful for tracking changes in JSON data, synchronizing objects, and implementing undo/redo functionality.
Pros
- Supports both browser and Node.js environments
- Provides visual diff rendering for easy comparison
- Offers customizable diff and patch algorithms
- Includes delta compression for efficient storage of differences
Cons
- May have performance issues with very large JSON objects
- Documentation could be more comprehensive
- Limited support for complex data structures like circular references
- Lacks built-in support for some advanced use cases (e.g., three-way merge)
Code Examples
- Basic diffing and patching:
import { create } from 'jsondiffpatch';
const jsondiffpatch = create();
const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 3, c: 4 };
const delta = jsondiffpatch.diff(obj1, obj2);
console.log(delta); // { b: [2, 3], c: [4] }
jsondiffpatch.patch(obj1, delta);
console.log(obj1); // { a: 1, b: 3, c: 4 }
- Visual diff rendering:
import { create, formatters } from 'jsondiffpatch';
const jsondiffpatch = create();
const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 3, c: 4 };
const delta = jsondiffpatch.diff(obj1, obj2);
const html = formatters.html.format(delta);
document.getElementById('diff').innerHTML = html;
- Custom diff filter:
import { create } from 'jsondiffpatch';
const jsondiffpatch = create({
objectHash: (obj) => obj.id,
arrays: {
detectMove: true,
includeValueOnMove: false
}
});
const arr1 = [{ id: 1, value: 'a' }, { id: 2, value: 'b' }];
const arr2 = [{ id: 2, value: 'b' }, { id: 1, value: 'c' }];
const delta = jsondiffpatch.diff(arr1, arr2);
console.log(delta); // { _t: 'a', 0: [{ id: 1, value: 'a' }, { id: 2, value: 'b' }, 0, 3], 1: [{ id: 2, value: 'b' }, 0, 0, 3], 2: [{ id: 1, value: 'c' }] }
Getting Started
To use jsondiffpatch in your project, follow these steps:
-
Install the library:
npm install jsondiffpatch
-
Import and create an instance:
import { create } from 'jsondiffpatch'; const jsondiffpatch = create();
-
Use the
diff
andpatch
methods:const delta = jsondiffpatch.diff(obj1, obj2); jsondiffpatch.patch(obj1, delta);
For more advanced usage and configuration options, refer to the official documentation.
Competitor Comparisons
Javascript utility for calculating deep difference, capturing changes, and applying changes across objects; for nodejs and the browser.
Pros of diff
- Lightweight and focused solely on object diffing
- Simple API with straightforward usage
- Supports custom equality comparisons for complex objects
Cons of diff
- Limited features compared to jsondiffpatch
- No built-in visualization or patching functionality
- Less active development and community support
Code Comparison
diff:
var diff = require('diff');
var result = diff(obj1, obj2);
jsondiffpatch:
var jsondiffpatch = require('jsondiffpatch');
var delta = jsondiffpatch.diff(obj1, obj2);
Key Differences
- diff focuses solely on generating differences between objects
- jsondiffpatch offers a more comprehensive suite of tools, including diffing, patching, and visualization
- diff provides a simpler API, while jsondiffpatch offers more advanced features and customization options
- jsondiffpatch has better support for arrays and nested structures
- diff allows for custom equality comparisons, which can be useful for complex objects
Use Cases
- Choose diff for simple object comparison tasks with minimal overhead
- Opt for jsondiffpatch when you need a full-featured solution with patching and visualization capabilities
- Consider diff if you require custom equality comparisons for specific object types
- Use jsondiffpatch for projects that involve complex data structures or require visual representation of differences
A fast, zero dependency object and array comparison library. Significantly faster than most other deep comparison libraries and has full TypeScript support.
Pros of microdiff
- Significantly smaller package size (1.5kB vs 21.7kB for jsondiffpatch)
- Faster performance for small to medium-sized objects
- Simpler API with fewer dependencies
Cons of microdiff
- Less feature-rich compared to jsondiffpatch (e.g., lacks visual diff)
- May not handle complex nested structures as efficiently
- Limited customization options for diff output
Code Comparison
microdiff:
import { diff } from 'microdiff';
const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 3, c: 4 };
console.log(diff(obj1, obj2));
jsondiffpatch:
import { create } from 'jsondiffpatch';
const jsondiffpatch = create();
const obj1 = { a: 1, b: 2 };
const obj2 = { a: 1, b: 3, c: 4 };
console.log(jsondiffpatch.diff(obj1, obj2));
Both libraries provide efficient ways to compare JavaScript objects, but microdiff offers a more lightweight solution with a simpler API. jsondiffpatch, while larger, provides more advanced features and customization options. The choice between the two depends on the specific requirements of your project, such as package size constraints, performance needs, and the complexity of the objects being compared.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
jsondiffpatch
Diff & patch JavaScript objects
Live Demo
- min+gzipped ~ 16KB
- browser and server (ESM-only)
- (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 browser that supports ES6
- Node.js 18, 20+
Usage
// sample data
const country = {
name: 'Argentina',
capital: 'Buenos Aires',
independence: new Date(1816, 6, 9),
unasur: true,
};
// clone country, using dateReviver for Date objects
const country2 = JSON.parse(JSON.stringify(country), jsondiffpatch.dateReviver);
// make some changes
country2.name = 'Republica Argentina';
country2.population = 41324992;
delete country2.capital;
const delta = jsondiffpatch.diff(country, country2);
assertSame(delta, {
name: ['Argentina', 'Republica Argentina'], // old value, new value
population: ['41324992'], // new value
capital: ['Buenos Aires', 0, 0], // deleted
});
// patch original
jsondiffpatch.patch(country, delta);
// reverse diff
const reverseDelta = jsondiffpatch.reverse(delta);
// also country2 can be return to original value with: jsondiffpatch.unpatch(country2, delta);
const delta2 = jsondiffpatch.diff(country, country2);
assert(delta2 === undefined);
// undefined => no difference
Array diffing:
// sample data
const 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,
},
],
};
// clone country
const country2 = JSON.parse(JSON.stringify(country));
// delete Cordoba
country.cities.splice(1, 1);
// add La Plata
country.cities.splice(4, 0, {
name: 'La Plata',
});
// modify Rosario, and move it
const rosario = country.cities.splice(1, 1)[0];
rosario.population += 1234;
country.cities.push(rosario);
// create a configured instance, match objects by name
const diffpatcher = jsondiffpatch.create({
objectHash: function (obj) {
return obj.name;
},
});
const delta = diffpatcher.diff(country, country2);
assertSame(delta, {
cities: {
_t: 'a', // indicates this node is an array (not an object)
1: [
// inserted at index 1
{
name: 'Cordoba',
population: 1430023,
},
],
2: {
// population modified at index 2 (Rosario)
population: [1137520, 1136286],
},
_3: [
// removed from index 3
{
name: 'La Plata',
},
0,
0,
],
_4: [
// move from index 4 to index 2
'',
2,
3,
],
},
});
For more example cases (nested objects or arrays, long text diffs) check packages/jsondiffpatch/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
import * as jsondiffpatch from 'jsondiffpatch';
const jsondiffpatchInstance = jsondiffpatch.create(options);
browser
In a browser, you can load a bundle using a tool like esm.sh or Skypack.
Options
import * as jsondiffpatch from 'jsondiffpatch';
// Only import if you want text diffs using diff-match-patch
import DiffMatchPatch from 'diff-match-patch';
const jsondiffpatchInstance = jsondiffpatch.create({
// used to match objects when diffing arrays, by default only === operator is used
objectHash: function (obj) {
// this function is used only to when objects are not equal by ref
return obj._id || obj.id;
},
arrays: {
// default true, detect items moved inside the array (otherwise they will be registered as remove+add)
detectMove: true,
// default false, the value of items moved is not included in deltas
includeValueOnMove: false,
},
textDiff: {
// If using text diffs, it's required to pass in the diff-match-patch library in through this proprty.
// Alternatively, you can import jsondiffpatch using `jsondiffpatch/with-text-diffs` to avoid having to pass in diff-match-patch through the options.
diffMatchPatch: DiffMatchPatch,
// default 60, minimum string length (left and right sides) to use text diff algorythm: google-diff-match-patch
minLength: 60,
},
propertyFilter: function (name, context) {
/*
this optional function can be specified to ignore object properties (eg. volatile data)
name: property name, present in either context.left or context.right objects
context: the diff context (has context.left and context.right objects)
*/
return name.slice(0, 1) !== '$';
},
cloneDiffValues: false /* default false. if true, values in the obtained delta will be cloned
(using jsondiffpatch.clone by default), to ensure delta keeps no references to left or right objects. this becomes useful if you're diffing and patching the same objects multiple times without serializing deltas.
instead of true, a function can be specified here to provide a custom clone(value)
*/,
});
Visual Diff
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="./style.css" type="text/css" />
<link
rel="stylesheet"
href="https://esm.sh/jsondiffpatch@0.6.0/lib/formatters/styles/html.css"
type="text/css"
/>
<link
rel="stylesheet"
href="https://esm.sh/jsondiffpatch@0.6.0/lib/formatters/styles/annotated.css"
type="text/css"
/>
</head>
<body>
<div id="visual"></div>
<hr />
<div id="annotated"></div>
<script type="module">
import * as jsondiffpatch from 'https://esm.sh/jsondiffpatch@0.6.0';
import * as annotatedFormatter from 'https://esm.sh/jsondiffpatch@0.6.0/formatters/annotated';
import * as htmlFormatter from 'https://esm.sh/jsondiffpatch@0.6.0/formatters/html';
const left = { a: 3, b: 4 };
const right = { a: 5, c: 9 };
const delta = jsondiffpatch.diff(left, right);
// beautiful html diff
document.getElementById('visual').innerHTML = htmlFormatter.format(
delta,
left,
);
// self-explained json
document.getElementById('annotated').innerHTML =
annotatedFormatter.format(delta, left);
</script>
</body>
</html>
To see formatters in action check the Live Demo.
For more details check Formatters documentation
Console
# diff two json files, colored output (using chalk lib)
./node_modules/.bin/jsondiffpatch ./docs/demo/left.json ./docs/demo/right.json
# or install globally
npm install -g jsondiffpatch
jsondiffpatch ./docs/demo/left.json ./docs/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.
Top Related Projects
Javascript utility for calculating deep difference, capturing changes, and applying changes across objects; for nodejs and the browser.
A fast, zero dependency object and array comparison library. Significantly faster than most other deep comparison libraries and has full TypeScript support.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot