CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-jsondiffpatch

JSON diff & patch library with support for objects, arrays, text diffs, and multiple output formats

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

formatters.mddocs/

Formatters

Multiple output formats for visualizing and processing diffs including console output, HTML visualization, JSON Patch compatibility, and annotated formatting.

Capabilities

Console Formatter

Formats deltas for console output with colors and indentation for easy reading.

import * as console from "jsondiffpatch/formatters/console";

/**
 * Format delta for console output with colors
 * @param delta - Delta to format
 * @param left - Original value for context
 * @returns Formatted string with ANSI colors
 */
function format(delta: Delta, left?: unknown): string;

/**
 * Log formatted delta directly to console
 * @param delta - Delta to log
 * @param left - Original value for context
 */
function log(delta: Delta, left?: unknown): void;

Usage Examples:

import { diff } from "jsondiffpatch";
import * as console from "jsondiffpatch/formatters/console";

const delta = diff({ name: "Alice", age: 25 }, { name: "Alice", age: 26, role: "admin" });

// Format as string
const formatted = console.format(delta);
console.log(formatted);

// Direct logging
console.log(delta);

HTML Formatter

Formats deltas as HTML for rich visual diff presentation with expandable sections and styling.

import * as html from "jsondiffpatch/formatters/html";

/**
 * Format delta as HTML with CSS classes for styling
 * @param delta - Delta to format
 * @param left - Original value for context
 * @returns HTML string with diff visualization
 */
function format(delta: Delta, left?: unknown): string;

/**
 * Show or hide unchanged values in HTML output
 * @param show - Whether to show unchanged values
 * @param node - DOM element containing diff (optional)
 * @param delay - Animation delay in milliseconds (optional)
 */
function showUnchanged(show?: boolean, node?: Element, delay?: number): void;

/**
 * Hide unchanged values in HTML output
 * @param node - DOM element containing diff (optional)
 * @param delay - Animation delay in milliseconds (optional)
 */
function hideUnchanged(node?: Element, delay?: number): void;

Usage Examples:

import { diff } from "jsondiffpatch";
import * as html from "jsondiffpatch/formatters/html";

const delta = diff(
  { users: [{ name: "Alice", age: 25 }, { name: "Bob", age: 30 }] },
  { users: [{ name: "Alice", age: 26 }, { name: "Bob", age: 30 }, { name: "Charlie", age: 35 }] }
);

// Generate HTML
const htmlDiff = html.format(delta);
document.getElementById('diff-container').innerHTML = htmlDiff;

// Control unchanged value visibility
html.showUnchanged(false); // Hide unchanged values globally
html.hideUnchanged(document.getElementById('diff-container'), 300);

Annotated Formatter

Formats deltas with human-readable annotations explaining each change.

import * as annotated from "jsondiffpatch/formatters/annotated";

/**
 * Format delta with descriptive annotations
 * @param delta - Delta to format
 * @param left - Original value for context
 * @returns Annotated string describing changes
 */
function format(delta: Delta, left?: unknown): string;

Usage Examples:

import { diff } from "jsondiffpatch";
import * as annotated from "jsondiffpatch/formatters/annotated";

const delta = diff({ name: "Alice", age: 25 }, { name: "Alice", age: 26, role: "admin" });
const description = annotated.format(delta);
console.log(description);
// Output: "age: [25] => [26], role: added [admin]"

JSON Patch Formatter

Converts deltas to RFC 6902 JSON Patch format for standards-compliant diff operations.

import * as jsonpatch from "jsondiffpatch/formatters/jsonpatch";

/**
 * Convert delta to JSON Patch operations array
 * @param delta - Delta to convert
 * @returns Array of JSON Patch operations
 */
function format(delta: Delta): Op[];

/**
 * Log JSON Patch operations to console
 * @param delta - Delta to log as JSON Patch
 */
function log(delta: Delta): void;

/**
 * Apply JSON Patch operations to target object (RFC 6902)
 * @param target - Object to patch
 * @param patch - Array of JSON Patch operations
 */
const patch: (target: unknown, patch: JsonPatchOp[]) => void;

// JSON Patch operation types
interface AddOp {
  op: "add";
  path: string;
  value: any;
}

interface RemoveOp {
  op: "remove";
  path: string;
}

interface ReplaceOp {
  op: "replace";
  path: string;
  value: any;
}

interface MoveOp {
  op: "move";
  from: string;
  path: string;
}

type Op = AddOp | RemoveOp | ReplaceOp | MoveOp;

// Extended operations for RFC 6902 compliance
interface CopyOp {
  op: "copy";
  from: string;
  path: string;
}

interface TestOp {
  op: "test";
  path: string;
  value: any;
}

type JsonPatchOp = Op | CopyOp | TestOp;

Usage Examples:

import { diff } from "jsondiffpatch";
import * as jsonpatch from "jsondiffpatch/formatters/jsonpatch";

const delta = diff({ name: "Alice", age: 25 }, { name: "Alice", age: 26, role: "admin" });

// Convert to JSON Patch
const patches = jsonpatch.format(delta);
console.log(patches);
// Result: [
//   { op: "replace", path: "/age", value: 26 },
//   { op: "add", path: "/role", value: "admin" }
// ]

// Apply JSON Patch to object
const target = { name: "Alice", age: 25 };
jsonpatch.patch(target, patches);
console.log(target);
// Result: { name: "Alice", age: 26, role: "admin" }

// Direct logging
jsonpatch.log(delta);

JSON Patch Apply

Complete RFC 6902 JSON Patch implementation for applying JSON Patch operations with atomic rollback support.

import { applyJsonPatchRFC6902, type JsonPatchOp } from "jsondiffpatch/formatters/jsonpatch-apply";

/**
 * Apply JSON Patch operations with atomic rollback on failure
 * @param target - Object to patch (will be modified in place)
 * @param patch - Array of JSON Patch operations
 * @throws Error if any operation fails (with complete rollback)
 */
const applyJsonPatchRFC6902: (target: unknown, patch: JsonPatchOp[]) => void;

// Extended JSON Patch operation types (RFC 6902 compliant)
interface CopyOp {
  op: "copy";
  from: string;
  path: string;
}

interface TestOp {
  op: "test";
  path: string;
  value: unknown;
}

// Complete JSON Patch operation union including RFC 6902 extensions
type JsonPatchOp = Op | CopyOp | TestOp;

Usage Examples:

import { applyJsonPatchRFC6902 } from "jsondiffpatch/formatters/jsonpatch-apply";

// Apply RFC 6902 compliant JSON Patch
const target = { users: [{ name: "Alice", age: 25 }], count: 1 };
const patch = [
  { op: "replace", path: "/users/0/age", value: 26 },
  { op: "add", path: "/users/-", value: { name: "Bob", age: 30 } },
  { op: "copy", from: "/users/0/name", path: "/lastUser" },
  { op: "test", path: "/count", value: 1 },
  { op: "replace", path: "/count", value: 2 }
];

try {
  applyJsonPatchRFC6902(target, patch);
  console.log(target);
  // Result: { 
  //   users: [{ name: "Alice", age: 26 }, { name: "Bob", age: 30 }], 
  //   count: 2, 
  //   lastUser: "Alice" 
  // }
} catch (error) {
  // If any operation fails, all changes are rolled back atomically
  console.error("Patch failed:", error.message);
  // target is unchanged from original state
}

// Test operation validation
const testPatch = [
  { op: "test", path: "/users/0/age", value: 25 }, // This will pass
  { op: "test", path: "/count", value: 5 }         // This will fail
];

try {
  applyJsonPatchRFC6902(target, testPatch);
} catch (error) {
  console.log("Test failed - object unchanged");
}

Key Features:

  • Atomic Operations: Complete rollback if any operation in the patch fails
  • RFC 6902 Compliance: Full support for add, remove, replace, move, copy, and test operations
  • Path Validation: Proper JSON Pointer path parsing with escape sequence support
  • Error Handling: Detailed error messages with context about failed operations
  • Array Handling: Correct index-based operations for array manipulation

CSS Styles

HTML formatter includes CSS files for styling:

// Import CSS for HTML formatter styling
import "jsondiffpatch/formatters/styles/html.css";
import "jsondiffpatch/formatters/styles/annotated.css";

Error Handling

All formatters handle invalid or undefined deltas gracefully:

  • undefined or null deltas return empty output
  • Malformed deltas are processed with best-effort formatting
  • HTML formatter escapes content to prevent XSS
  • JSON Patch formatter validates operations before applying

docs

core-operations.md

diffpatcher-class.md

formatters.md

index.md

options-configuration.md

tile.json