百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
J

json-diff-ts

> 编程语言
开源

一个用 TypeScript 编写的 JavaScript 差异工具。

192 stars0 点赞2 次浏览
访问官网GitHub

工具介绍

一个用 TypeScript 编写的 JavaScript 差异工具。

json-diff-ts

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).

Why Index-Based Diffing Breaks

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:

typescript
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:

json
{
  "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:

typescript
// Clone before applying — applyAtom mutates the input object
const updated  = applyAtom(structuredClone(before), atom);  // updated === after
const restored = revertAtom(structuredClone(updated), atom); // restored === before

Quick Start

…

That's it. atom is a plain JSON object you can store in a database, send over HTTP, or consume in any language.

Installation

bash
npm install json-diff-ts
typescript
// ESM / TypeScript
import { diffAtom, applyAtom, revertAtom } from 'json-diff-ts';

// CommonJS
const { diffAtom, applyAtom, revertAtom } = require('json-diff-ts');

What is JSON Atom?

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:

  • Three operations -- add, remove, replace. Nothing else to learn.
  • JSONPath-based paths -- $.items[?(@.id==1)].name identifies elements by key, not index.
  • Reversible by default -- every replace and remove includes oldValue for undo.
  • Self-identifying -- the format field makes atoms discoverable without external context.
  • Extension-friendly -- unknown properties are preserved; x_-prefixed properties are future-safe.

JSON Atom vs JSON Patch (RFC 6902)

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

JSON Atom API

diffAtom -- Compute an Atom

typescript
const atom = diffAtom(
  { user: { name: 'Alice', role: 'viewer' } },
  { user: { name: 'Alice', role: 'admin' } }
);
// atom.operations → [{ op: 'replace', path: '$.user.role', value: 'admin', oldValue: 'viewer' }]

Keyed Arrays

Match array elements by identity key. Filter paths use canonical typed literals per the spec:

typescript
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' }]

Non-reversible Mode

Omit oldValue fields when you don't need undo:

typescript
const atom = diffAtom(source, target, { reversible: false });

applyAtom -- Apply an Atom

Applies operations sequentially. Always use the return value (required for root-level replacements):

typescript
const result = applyAtom(structuredClone(source), atom);

revertAtom -- Revert an Atom

Computes the inverse and applies it. Requires oldValue on all replace and remove operations:

typescript
const original = revertAtom(structuredClone(target), atom);

invertAtom -- Compute the Inverse

Returns a new atom that undoes the original (spec Section 9.2):

typescript
const inverse = invertAtom(atom);
// add ↔ remove, replace swaps value/oldValue, order reversed

validateAtom -- Validate Structure

typescript
const { valid, errors } = validateAtom(maybeAtom);

API Reference

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

AtomOptions

Extends the base Options interface:

typescript
interface AtomOptions extends Options {
  reversible?: boolean;       // Include oldValue for undo. Default: true
  arrayIdentityKeys?: Record;
  keysToSkip?: readonly string[];
}

Atom Workflow Helpers

Transform, inspect, and compact atoms for workflow automation.

squashAtoms -- Compact Multiple Atoms

Combine 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 Transformations

All transforms are immutable — they return new atoms without modifying the original:

typescript
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 Introspection

Separate spec-defined fields from extension properties:

typescript
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 Introspection

Extract the terminal property name from an operation's path:

typescript
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)

Comparison Serialization

Serialize enriched comparison trees to plain objects or flat change lists.

…

Practical Examples

Audit Log

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.

Undo / Redo Stack

Build undo/redo for any JSON state object. Atoms are small (only changed fields), reversible, and serializable:

…

Data Synchronization

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:

…

Bridge: v4 Changeset JSON Atom

Convert between the legacy internal format and JSON Atom:

typescript
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· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

TypeScript

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言