一个用 TypeScript 编写的 JavaScript 差异工具。
Deterministic JSON state transitions with key-based array identity. A TypeScript JSON diff library that computes, applies, and reverts atomic changes using the JSON Atom wire format -- a JSON Patch alternative with stable array paths, built-in undo/redo for JSON, and language-agnostic state synchronization.
Zero dependencies. TypeScript-first. ESM + CommonJS. Trusted by thousands of developers (500K+ weekly npm downloads).
Most JSON diff libraries track array changes by position. Insert one element at the start and every path shifts:
Remove /items/0 ← was actually "Widget"
Add /items/0 ← now it's "NewItem"
Update /items/1 ← this used to be /items/0
...This makes diffs fragile -- you can't store them, replay them reliably, or build audit logs on top of them. Reorder the array and every operation is wrong. This is the fundamental problem with index-based formats like JSON Patch (RFC 6902): paths like /items/0 are positional, so any insertion, deletion, or reorder invalidates every subsequent path.
json-diff-ts solves this with key-based identity. Array elements are matched by a stable key (id, sku, or any field), and paths use JSONPath filter expressions that survive insertions, deletions, and reordering:
import { diffAtom, applyAtom, revertAtom } from 'json-diff-ts';
const before = {
items: [
{ id: 1, name: 'Widget', price: 9.99 },
{ id: 2, name: 'Gadget', price: 24.99 },
],
};
const after = {
items: [
{ id: 2, name: 'Gadget', price: 24.99 }, // reordered
{ id: 1, name: 'Widget Pro', price: 14.99 }, // renamed + repriced
{ id: 3, name: 'Doohickey', price: 4.99 }, // added
],
};
const atom = diffAtom(before, after, { arrayIdentityKeys: { items: 'id' } });The atom tracks what changed, not where it moved:
{
"format": "json-atom",
"version": 1,
"operations": [
{ "op": "replace", "path": "$.items[?(@.id==1)].name", "value": "Widget Pro", "oldValue": "Widget" },
{ "op": "replace", "path": "$.items[?(@.id==1)].price", "value": 14.99, "oldValue": 9.99 },
{ "op": "add", "path": "$.items[?(@.id==3)]", "value": { "id": 3, "name": "Doohickey", "price": 4.99 } }
]
}Apply forward to get the new state, or revert to restore the original:
// Clone before applying — applyAtom mutates the input object
const updated = applyAtom(structuredClone(before), atom); // updated === after
const restored = revertAtom(structuredClone(updated), atom); // restored === before…That's it. atom is a plain JSON object you can store in a database, send over HTTP, or consume in any language.
npm install json-diff-ts// ESM / TypeScript
import { diffAtom, applyAtom, revertAtom } from 'json-diff-ts';
// CommonJS
const { diffAtom, applyAtom, revertAtom } = require('json-diff-ts');JSON Atom is a specification for representing atomic changes to JSON documents. json-diff-ts is the originating implementation from which the spec was derived.
json-atom-format (specification)
├── json-diff-ts (TypeScript implementation) ← this package
└── json-atom-py (Python implementation)The specification defines the wire format. Each language implementation produces and consumes compatible atoms.
An atom is a self-describing JSON document you can store, transmit, and consume in any language:
add, remove, replace. Nothing else to learn.$.items[?(@.id==1)].name identifies elements by key, not index.replace and remove includes oldValue for undo.format field makes atoms discoverable without external context.x_-prefixed properties are future-safe.JSON Patch uses JSON Pointer paths like /items/0 that reference array elements by index. When an element is inserted at position 0, every subsequent path shifts -- /items/1 now points to what was /items/0. This makes stored patches unreliable for JSON change tracking, audit logs, or undo/redo across time.
JSON Atom uses JSONPath filter expressions like $.items[?(@.id==1)] that identify elements by a stable key. The path stays valid regardless of insertions, deletions, or reordering.
| JSON Atom | JSON Patch (RFC 6902) | |
|---|---|---|
| Path syntax | JSONPath ($.items[?(@.id==1)]) |
JSON Pointer (/items/0) |
| Array identity | Key-based -- survives reorder | Index-based -- breaks on insert/delete |
| Reversibility | Built-in oldValue |
Not supported |
| Self-describing | format field in envelope |
No envelope |
| Specification | json-atom-format | RFC 6902 |
diffAtom -- Compute an Atomconst atom = diffAtom(
{ user: { name: 'Alice', role: 'viewer' } },
{ user: { name: 'Alice', role: 'admin' } }
);
// atom.operations → [{ op: 'replace', path: '$.user.role', value: 'admin', oldValue: 'viewer' }]Match array elements by identity key. Filter paths use canonical typed literals per the spec:
const atom = diffAtom(
{ users: [{ id: 1, role: 'viewer' }, { id: 2, role: 'editor' }] },
{ users: [{ id: 1, role: 'admin' }, { id: 2, role: 'editor' }] },
{ arrayIdentityKeys: { users: 'id' } }
);
// atom.operations → [{ op: 'replace', path: '$.users[?(@.id==1)].role', value: 'admin', oldValue: 'viewer' }]Omit oldValue fields when you don't need undo:
const atom = diffAtom(source, target, { reversible: false });applyAtom -- Apply an AtomApplies operations sequentially. Always use the return value (required for root-level replacements):
const result = applyAtom(structuredClone(source), atom);revertAtom -- Revert an AtomComputes the inverse and applies it. Requires oldValue on all replace and remove operations:
const original = revertAtom(structuredClone(target), atom);invertAtom -- Compute the InverseReturns a new atom that undoes the original (spec Section 9.2):
const inverse = invertAtom(atom);
// add ↔ remove, replace swaps value/oldValue, order reversedvalidateAtom -- Validate Structureconst { valid, errors } = validateAtom(maybeAtom);| Function | Signature | Description |
|---|---|---|
diffAtom |
(oldObj, newObj, options?) => IJsonAtom |
Compute a canonical JSON Atom |
applyAtom |
(obj, atom) => any |
Apply an atom sequentially. Returns the result |
revertAtom |
(obj, atom) => any |
Revert a reversible atom |
invertAtom |
(atom) => IJsonAtom |
Compute the inverse atom |
validateAtom |
(atom) => { valid, errors } |
Structural validation |
toAtom |
(changeset, options?) => IJsonAtom |
Bridge: v4 changeset to JSON Atom |
fromAtom |
(atom) => IAtomicChange[] |
Bridge: JSON Atom to v4 atomic changes |
squashAtoms |
(source, atoms, options?) => IJsonAtom |
Compact multiple atoms into one net-effect atom |
atomMap |
(atom, fn) => IJsonAtom |
Transform each operation in an atom |
atomStamp |
(atom, extensions) => IJsonAtom |
Set extension properties on all operations |
atomGroupBy |
(atom, keyFn) => Record |
Group operations into sub-atoms |
operationSpecDict |
(op) => IAtomOperation |
Strip extension properties from operation |
operationExtensions |
(op) => Record |
Get extension properties from operation |
atomSpecDict |
(atom) => IJsonAtom |
Strip all extensions from atom |
atomExtensions |
(atom) => Record |
Get envelope extensions from atom |
leafProperty |
(op) => string | null |
Terminal property name from operation path |
Extends the base Options interface:
interface AtomOptions extends Options {
reversible?: boolean; // Include oldValue for undo. Default: true
arrayIdentityKeys?: Record;
keysToSkip?: readonly string[];
}Transform, inspect, and compact atoms for workflow automation.
squashAtoms -- Compact Multiple AtomsCombine a sequence of atoms into a single net-effect atom. Useful for compacting audit logs or collapsing undo history:
…Options: reversible, arrayIdentityKeys, target (pre-computed final state), verifyTarget (default: true).
atomMap / atomStamp / atomGroupBy -- Atom TransformationsAll transforms are immutable — they return new atoms without modifying the original:
import { diffAtom, atomMap, atomStamp, atomGroupBy } from 'json-diff-ts';
const atom = diffAtom(
{ name: 'Alice', age: 30, role: 'viewer' },
{ name: 'Bob', age: 31, status: 'active' }
);
// Stamp metadata onto every operation
const stamped = atomStamp(atom, { x_author: 'system', x_ts: Date.now() });
// Transform operations
const prefixed = atomMap(atom, (op) => ({
...op,
path: op.path.replace('$', '$.data'),
}));
// Group by operation type
const groups = atomGroupBy(atom, (op) => op.op);
// groups => { replace: IJsonAtom, add: IJsonAtom, remove: IJsonAtom }operationSpecDict / atomSpecDict -- Spec IntrospectionSeparate spec-defined fields from extension properties:
import { operationSpecDict, operationExtensions, atomSpecDict } from 'json-diff-ts';
const op = { op: 'replace', path: '$.name', value: 'Bob', x_author: 'system' };
operationSpecDict(op); // { op: 'replace', path: '$.name', value: 'Bob' }
operationExtensions(op); // { x_author: 'system' }
// Strip all extensions from an atom
const clean = atomSpecDict(atom);leafProperty -- Path IntrospectionExtract the terminal property name from an operation's path:
import { leafProperty } from 'json-diff-ts';
leafProperty({ op: 'replace', path: '$.user.name' }); // 'name'
leafProperty({ op: 'add', path: '$.items[?(@.id==1)]' }); // null (filter)
leafProperty({ op: 'replace', path: '$' }); // null (root)Serialize enriched comparison trees to plain objects or flat change lists.
…Store every change to a document as a reversible atom. Each entry records who changed what, when, and can be replayed or reverted independently -- a complete JSON change tracking system:
…Because every atom is self-describing JSON, your audit log is queryable, storable in any database, and readable from any language.
Build undo/redo for any JSON state object. Atoms are small (only changed fields), reversible, and serializable:
…Send only what changed between client and server. Atoms are compact -- a single field change in a 10KB document produces a few bytes of atom, making state synchronization efficient over the wire:
…Convert between the legacy internal format and JSON Atom:
import { diff, toAtom, fromAtom, unatomizeChangeset } from 'json-diff-ts';
// v4 changeset → JSON Atom
const changeset = diff(source, target, { arrayIdentityKeys: { items: 'id' } });
const atom = toAtom(changeset);
// JSON Atom → v4 atomic changes
const atoms = fromAtom(atom);
// v4 atomic changes → hierarchical changeset (if needed)
const cs = unatomizeChangeset(atoms);Note: toAtom is a best-effort bridge. Filter literals
暂无开放 Issues,或尚未同步最近议题。