0
# Formatters
1
2
Multiple output formats for visualizing and processing diffs including console output, HTML visualization, JSON Patch compatibility, and annotated formatting.
3
4
## Capabilities
5
6
### Console Formatter
7
8
Formats deltas for console output with colors and indentation for easy reading.
9
10
```javascript { .api }
11
import * as console from "jsondiffpatch/formatters/console";
12
13
/**
14
* Format delta for console output with colors
15
* @param delta - Delta to format
16
* @param left - Original value for context
17
* @returns Formatted string with ANSI colors
18
*/
19
function format(delta: Delta, left?: unknown): string;
20
21
/**
22
* Log formatted delta directly to console
23
* @param delta - Delta to log
24
* @param left - Original value for context
25
*/
26
function log(delta: Delta, left?: unknown): void;
27
```
28
29
**Usage Examples:**
30
31
```javascript
32
import { diff } from "jsondiffpatch";
33
import * as console from "jsondiffpatch/formatters/console";
34
35
const delta = diff({ name: "Alice", age: 25 }, { name: "Alice", age: 26, role: "admin" });
36
37
// Format as string
38
const formatted = console.format(delta);
39
console.log(formatted);
40
41
// Direct logging
42
console.log(delta);
43
```
44
45
### HTML Formatter
46
47
Formats deltas as HTML for rich visual diff presentation with expandable sections and styling.
48
49
```javascript { .api }
50
import * as html from "jsondiffpatch/formatters/html";
51
52
/**
53
* Format delta as HTML with CSS classes for styling
54
* @param delta - Delta to format
55
* @param left - Original value for context
56
* @returns HTML string with diff visualization
57
*/
58
function format(delta: Delta, left?: unknown): string;
59
60
/**
61
* Show or hide unchanged values in HTML output
62
* @param show - Whether to show unchanged values
63
* @param node - DOM element containing diff (optional)
64
* @param delay - Animation delay in milliseconds (optional)
65
*/
66
function showUnchanged(show?: boolean, node?: Element, delay?: number): void;
67
68
/**
69
* Hide unchanged values in HTML output
70
* @param node - DOM element containing diff (optional)
71
* @param delay - Animation delay in milliseconds (optional)
72
*/
73
function hideUnchanged(node?: Element, delay?: number): void;
74
```
75
76
**Usage Examples:**
77
78
```javascript
79
import { diff } from "jsondiffpatch";
80
import * as html from "jsondiffpatch/formatters/html";
81
82
const delta = diff(
83
{ users: [{ name: "Alice", age: 25 }, { name: "Bob", age: 30 }] },
84
{ users: [{ name: "Alice", age: 26 }, { name: "Bob", age: 30 }, { name: "Charlie", age: 35 }] }
85
);
86
87
// Generate HTML
88
const htmlDiff = html.format(delta);
89
document.getElementById('diff-container').innerHTML = htmlDiff;
90
91
// Control unchanged value visibility
92
html.showUnchanged(false); // Hide unchanged values globally
93
html.hideUnchanged(document.getElementById('diff-container'), 300);
94
```
95
96
### Annotated Formatter
97
98
Formats deltas with human-readable annotations explaining each change.
99
100
```javascript { .api }
101
import * as annotated from "jsondiffpatch/formatters/annotated";
102
103
/**
104
* Format delta with descriptive annotations
105
* @param delta - Delta to format
106
* @param left - Original value for context
107
* @returns Annotated string describing changes
108
*/
109
function format(delta: Delta, left?: unknown): string;
110
```
111
112
**Usage Examples:**
113
114
```javascript
115
import { diff } from "jsondiffpatch";
116
import * as annotated from "jsondiffpatch/formatters/annotated";
117
118
const delta = diff({ name: "Alice", age: 25 }, { name: "Alice", age: 26, role: "admin" });
119
const description = annotated.format(delta);
120
console.log(description);
121
// Output: "age: [25] => [26], role: added [admin]"
122
```
123
124
### JSON Patch Formatter
125
126
Converts deltas to RFC 6902 JSON Patch format for standards-compliant diff operations.
127
128
```javascript { .api }
129
import * as jsonpatch from "jsondiffpatch/formatters/jsonpatch";
130
131
/**
132
* Convert delta to JSON Patch operations array
133
* @param delta - Delta to convert
134
* @returns Array of JSON Patch operations
135
*/
136
function format(delta: Delta): Op[];
137
138
/**
139
* Log JSON Patch operations to console
140
* @param delta - Delta to log as JSON Patch
141
*/
142
function log(delta: Delta): void;
143
144
/**
145
* Apply JSON Patch operations to target object (RFC 6902)
146
* @param target - Object to patch
147
* @param patch - Array of JSON Patch operations
148
*/
149
const patch: (target: unknown, patch: JsonPatchOp[]) => void;
150
151
// JSON Patch operation types
152
interface AddOp {
153
op: "add";
154
path: string;
155
value: any;
156
}
157
158
interface RemoveOp {
159
op: "remove";
160
path: string;
161
}
162
163
interface ReplaceOp {
164
op: "replace";
165
path: string;
166
value: any;
167
}
168
169
interface MoveOp {
170
op: "move";
171
from: string;
172
path: string;
173
}
174
175
type Op = AddOp | RemoveOp | ReplaceOp | MoveOp;
176
177
// Extended operations for RFC 6902 compliance
178
interface CopyOp {
179
op: "copy";
180
from: string;
181
path: string;
182
}
183
184
interface TestOp {
185
op: "test";
186
path: string;
187
value: any;
188
}
189
190
type JsonPatchOp = Op | CopyOp | TestOp;
191
```
192
193
**Usage Examples:**
194
195
```javascript
196
import { diff } from "jsondiffpatch";
197
import * as jsonpatch from "jsondiffpatch/formatters/jsonpatch";
198
199
const delta = diff({ name: "Alice", age: 25 }, { name: "Alice", age: 26, role: "admin" });
200
201
// Convert to JSON Patch
202
const patches = jsonpatch.format(delta);
203
console.log(patches);
204
// Result: [
205
// { op: "replace", path: "/age", value: 26 },
206
// { op: "add", path: "/role", value: "admin" }
207
// ]
208
209
// Apply JSON Patch to object
210
const target = { name: "Alice", age: 25 };
211
jsonpatch.patch(target, patches);
212
console.log(target);
213
// Result: { name: "Alice", age: 26, role: "admin" }
214
215
// Direct logging
216
jsonpatch.log(delta);
217
```
218
219
### JSON Patch Apply
220
221
Complete RFC 6902 JSON Patch implementation for applying JSON Patch operations with atomic rollback support.
222
223
```javascript { .api }
224
import { applyJsonPatchRFC6902, type JsonPatchOp } from "jsondiffpatch/formatters/jsonpatch-apply";
225
226
/**
227
* Apply JSON Patch operations with atomic rollback on failure
228
* @param target - Object to patch (will be modified in place)
229
* @param patch - Array of JSON Patch operations
230
* @throws Error if any operation fails (with complete rollback)
231
*/
232
const applyJsonPatchRFC6902: (target: unknown, patch: JsonPatchOp[]) => void;
233
234
// Extended JSON Patch operation types (RFC 6902 compliant)
235
interface CopyOp {
236
op: "copy";
237
from: string;
238
path: string;
239
}
240
241
interface TestOp {
242
op: "test";
243
path: string;
244
value: unknown;
245
}
246
247
// Complete JSON Patch operation union including RFC 6902 extensions
248
type JsonPatchOp = Op | CopyOp | TestOp;
249
```
250
251
**Usage Examples:**
252
253
```javascript
254
import { applyJsonPatchRFC6902 } from "jsondiffpatch/formatters/jsonpatch-apply";
255
256
// Apply RFC 6902 compliant JSON Patch
257
const target = { users: [{ name: "Alice", age: 25 }], count: 1 };
258
const patch = [
259
{ op: "replace", path: "/users/0/age", value: 26 },
260
{ op: "add", path: "/users/-", value: { name: "Bob", age: 30 } },
261
{ op: "copy", from: "/users/0/name", path: "/lastUser" },
262
{ op: "test", path: "/count", value: 1 },
263
{ op: "replace", path: "/count", value: 2 }
264
];
265
266
try {
267
applyJsonPatchRFC6902(target, patch);
268
console.log(target);
269
// Result: {
270
// users: [{ name: "Alice", age: 26 }, { name: "Bob", age: 30 }],
271
// count: 2,
272
// lastUser: "Alice"
273
// }
274
} catch (error) {
275
// If any operation fails, all changes are rolled back atomically
276
console.error("Patch failed:", error.message);
277
// target is unchanged from original state
278
}
279
280
// Test operation validation
281
const testPatch = [
282
{ op: "test", path: "/users/0/age", value: 25 }, // This will pass
283
{ op: "test", path: "/count", value: 5 } // This will fail
284
];
285
286
try {
287
applyJsonPatchRFC6902(target, testPatch);
288
} catch (error) {
289
console.log("Test failed - object unchanged");
290
}
291
```
292
293
**Key Features:**
294
295
- **Atomic Operations**: Complete rollback if any operation in the patch fails
296
- **RFC 6902 Compliance**: Full support for add, remove, replace, move, copy, and test operations
297
- **Path Validation**: Proper JSON Pointer path parsing with escape sequence support
298
- **Error Handling**: Detailed error messages with context about failed operations
299
- **Array Handling**: Correct index-based operations for array manipulation
300
301
## CSS Styles
302
303
HTML formatter includes CSS files for styling:
304
305
```javascript
306
// Import CSS for HTML formatter styling
307
import "jsondiffpatch/formatters/styles/html.css";
308
import "jsondiffpatch/formatters/styles/annotated.css";
309
```
310
311
## Error Handling
312
313
All formatters handle invalid or undefined deltas gracefully:
314
- `undefined` or `null` deltas return empty output
315
- Malformed deltas are processed with best-effort formatting
316
- HTML formatter escapes content to prevent XSS
317
- JSON Patch formatter validates operations before applying