An experimental library to diff JSON objects/arrays by flattening them. It can create a patch between two JSON objects/arrays, and apply the patch to another JSON object/array. Use by bookmark-to-gist.
npm install flat-json-diff
import {diff, applyPatch} from "flat-json-diff";
const a = [
{title: "foo", tags: ["a", "b"]},
{title: "bar", tags: ["b", "c"]},
];
const b = [
{title: "foo", tags: ["a", "b", "d"]},
{title: "bar", tags: ["c"]},
{title: "baz", tags: []},
];
const patch = diff(a, b);
const c = applyPatch([
{title: "bak", tags: ["x"]},
{title: "foo", tags: []},
{title: "bar", tags: ["b"]},
], patch);
console.log(c);
// [
// { title: 'bak', tags: ["x"] }
// { title: 'foo', tags: ["d"] },
// { title: 'bar', tags: [] },
// { title: 'baz', tags: [] }
// ]The library flattens the JSON objects/arrays to diff-friendly lines, diffs the lines to create a patch.
When applying the patch, it flattens the target object/array to lines, apply the patch to the lines, and finally unflattens it back to JSON.
There are some limitations: https://github.com/kpdecker/jsdiff
Regardless of fuzzFactor, lines to be deleted in the hunk must be present for a hunk to match, and the context lines immediately before and after an insertion must match exactly.
- Modifying a deleted line/Deleting a modified line will always fail.
- When adding property, the property before/after the changed property must be the same. Ideally, adding an object property should always succeed.
Check the .d.ts file for TypeScript type definitions.
Because I'm working with bookmark JSON diff, it is crucial to detect move operations. Also bookmarks don't have an object ID, so most of the simple solutions won't work well.
- diff: The underlying diff library used in this project. It is designed for text diff.
Other json diff tools:
- rfc6902: Support remove, add, replace.
- mini-rfc6902: A minimal RFC6902 implementation.
- json-diff-ts: Support object ID. No move operation.
- diffptch: Treats arrays as non-ordered set.
- json-diff-kit: Support multiple array diff methods. No move operation.
- jsondiffpatch: Probably the most robust JSON diff library. Uses object hash to detect move operations.
The best solution should be something like:
- Suppose we have three versions: A -> B, A -> C, and we need a merge of B and C.
- Diff A -> B to get a patch P1.
- Diff A -> C to get a patch P2.
- According the information on A, merge P1 and P2 to get P3.
- Apply P3 to A to get the merged result.
When diffing arrays, it should calculate the smallest changes between two arrays, considering move, add, delete, and modify operations, with munkres or similar algorithms.
-
0.1.1 (Nov 28, 2025)
- Fix: include types.
-
0.1.0 (Nov 28, 2025)
- First release