JSON Formatter core library that renders JSON objects in HTML with collapsible navigation functionality.
npx @tessl/cli install tessl/npm-json-formatter-js@2.5.00
# JSON Formatter JS
1
2
A TypeScript library for rendering JSON objects in HTML with collapsible navigation, theming support, and interactive features like hover previews and expandable/collapsible tree structures.
3
4
## Package Information
5
6
- **Package Name**: json-formatter-js
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install json-formatter-js`
10
11
## Core Imports
12
13
```typescript
14
import JSONFormatter from "json-formatter-js";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const JSONFormatter = require("json-formatter-js");
21
```
22
23
Individual helper functions (if needed):
24
25
```typescript
26
import { getType, isObject, getObjectName, getValuePreview, getPreview, cssClass, createElement } from "json-formatter-js";
27
```
28
29
## Basic Usage
30
31
```typescript
32
import JSONFormatter from "json-formatter-js";
33
34
const jsonData = { name: "Alice", age: 30, hobbies: ["reading", "coding"] };
35
const formatter = new JSONFormatter(jsonData, 2);
36
document.body.appendChild(formatter.render());
37
```
38
39
## Architecture
40
41
JSON Formatter JS follows a class-based architecture where the main `JSONFormatter` class handles rendering JSON data as interactive HTML elements. It supports nested objects/arrays, customizable themes, animations, and various configuration options for controlling display behavior.
42
43
## Capabilities
44
45
### JSON Rendering
46
47
Core functionality for converting JSON data into interactive HTML elements with collapsible navigation.
48
49
```typescript { .api }
50
/**
51
* Main class for rendering JSON objects in HTML with collapsible navigation
52
*/
53
class JSONFormatter {
54
/**
55
* Creates a new JSONFormatter instance
56
* @param json - The JSON object/array to render (not a raw JSON string)
57
* @param open - Number of levels to expand initially (default: 1, use Infinity for fully expanded)
58
* @param config - Configuration options for appearance and behavior
59
* @param key - Internal parameter for nested rendering
60
* @param displayKey - Internal parameter for display formatting
61
* @param path - Internal parameter for path tracking
62
* @param arrayRange - Internal parameter for array chunking
63
*/
64
constructor(
65
json: any,
66
open?: number,
67
config?: JSONFormatterConfiguration,
68
key?: string,
69
displayKey?: string,
70
path?: string[],
71
arrayRange?: [number, number]
72
);
73
74
/**
75
* Renders the JSON formatter as an HTML element
76
* @returns HTMLDivElement containing the formatted JSON display
77
*/
78
render(): HTMLDivElement;
79
80
/**
81
* Toggles the open/closed state of the formatter
82
*/
83
toggleOpen(): void;
84
85
/**
86
* Opens the formatter to a specific depth level
87
* @param depth - Number of levels to expand (default: 1, use 0 to collapse all, Infinity to expand all)
88
*/
89
openAtDepth(depth?: number): void;
90
91
/**
92
* Generates inline preview text for hover functionality
93
* @returns String representation for hover preview
94
*/
95
getInlinepreview(): string;
96
}
97
```
98
99
### Configuration Options
100
101
Comprehensive configuration system for customizing appearance, behavior, and interaction patterns.
102
103
```typescript { .api }
104
interface JSONFormatterConfiguration {
105
/**
106
* Enable hover preview functionality
107
* @default false
108
*/
109
hoverPreviewEnabled?: boolean;
110
111
/**
112
* Maximum number of array items to show in hover preview
113
* Arrays larger than this show "Array[XXX]" format
114
* @default 100
115
*/
116
hoverPreviewArrayCount?: number;
117
118
/**
119
* Maximum number of object properties to show in hover preview
120
* Objects with more properties get truncated with "..."
121
* @default 5
122
*/
123
hoverPreviewFieldCount?: number;
124
125
/**
126
* Enable animation when expanding JSON objects
127
* @default true
128
*/
129
animateOpen?: boolean;
130
131
/**
132
* Enable animation when collapsing JSON objects
133
* @default true
134
*/
135
animateClose?: boolean;
136
137
/**
138
* Theme name for styling (e.g., 'dark')
139
* @default null
140
*/
141
theme?: string;
142
143
/**
144
* Use toJSON() method for object serialization when available
145
* Useful for Date objects, MongoDB ObjectIDs, etc.
146
* @default true
147
*/
148
useToJSON?: boolean;
149
150
/**
151
* Custom sorting function for object properties
152
* @default null
153
*/
154
sortPropertiesBy?: (a: string, b: string) => number;
155
156
/**
157
* Maximum items per array chunk (splits large arrays into groups)
158
* @default 100
159
*/
160
maxArrayItems?: number;
161
162
/**
163
* Add path data to DOM elements for correlating nodes to original JSON
164
* @default false
165
*/
166
exposePath?: boolean;
167
}
168
```
169
170
### Advanced Usage Patterns
171
172
Complex configuration and dynamic control examples for sophisticated use cases.
173
174
```typescript { .api }
175
// Theme configuration
176
const darkThemeConfig: JSONFormatterConfiguration = {
177
theme: 'dark',
178
hoverPreviewEnabled: true,
179
animateOpen: true,
180
animateClose: true
181
};
182
183
// Performance optimized for large datasets
184
const performanceConfig: JSONFormatterConfiguration = {
185
maxArrayItems: 50,
186
hoverPreviewArrayCount: 20,
187
hoverPreviewFieldCount: 3,
188
animateOpen: false,
189
animateClose: false
190
};
191
192
// Custom property sorting
193
const sortedConfig: JSONFormatterConfiguration = {
194
sortPropertiesBy: (a: string, b: string) => a.localeCompare(b)
195
};
196
197
// Dynamic control example
198
const formatter = new JSONFormatter(data, 1, darkThemeConfig);
199
const element = formatter.render();
200
document.body.appendChild(element);
201
202
// Programmatic expansion control
203
formatter.openAtDepth(0); // Collapse all
204
formatter.openAtDepth(Infinity); // Expand all
205
formatter.toggleOpen(); // Toggle current state
206
```
207
208
### Data Type Handling
209
210
Specialized rendering for different data types with automatic detection and formatting.
211
212
```typescript { .api }
213
// Supported data types with special handling:
214
215
// Date objects and date strings - automatically detected and styled
216
const dateData = {
217
created: new Date(),
218
modified: "2023-12-05T18:58:53.727Z",
219
legacy: "12/05/2023 6:58:53 PM"
220
};
221
222
// URL strings - automatically converted to clickable links
223
const urlData = {
224
homepage: "https://example.com",
225
api: "https://api.example.com/v1"
226
};
227
228
// Functions - display signature with collapsed body
229
const functionData = {
230
handler: function processData(input, options) {
231
return input.map(item => transform(item, options));
232
}
233
};
234
235
// Large arrays - automatically chunked for performance
236
const largeArrayData = {
237
items: new Array(500).fill(0).map((_, i) => ({ id: i, value: i * 2 }))
238
};
239
240
// Objects with toJSON - uses custom serialization
241
const customData = {
242
timestamp: new Date(), // Uses Date.prototype.toJSON()
243
// MongoDB ObjectId would also use toJSON()
244
};
245
```
246
247
### Error Handling and Edge Cases
248
249
Built-in handling for common edge cases and error conditions.
250
251
```typescript { .api }
252
// Safe handling of various edge cases:
253
254
// Null and undefined values
255
const edgeCaseData = {
256
nullValue: null,
257
undefinedValue: undefined,
258
emptyObject: {},
259
emptyArray: [],
260
emptyString: ""
261
};
262
263
// Objects without constructors
264
const objectWithoutConstructor = Object.create(null);
265
objectWithoutConstructor.data = "value";
266
267
// Circular references - handled via toJSON when useToJSON is true
268
const circularRef = { a: 1 };
269
circularRef.self = circularRef; // Only safe if object has toJSON method
270
271
// Functions with malformed signatures - gracefully handled
272
const malformedFunction = new Function("return 42");
273
274
// Very deep nesting
275
const deepObject = { level1: { level2: { level3: { level4: { value: "deep" } } } } };
276
277
// All these cases are handled gracefully by JSONFormatter
278
const formatter = new JSONFormatter(edgeCaseData);
279
```
280
281
### Helper Functions
282
283
Utility functions exported by the library for advanced use cases and custom implementations.
284
285
```typescript { .api }
286
/**
287
* Gets the type of a value, returning "null" for null objects
288
* @param value - Any value to check type for
289
* @returns Type string (JavaScript primitive types plus "array" and "null")
290
*/
291
function getType(value: any): string;
292
293
/**
294
* Determines if a value is an object (including arrays)
295
* @param value - Value to check
296
* @returns True if value is an object type
297
*/
298
function isObject(value: any): boolean;
299
300
/**
301
* Gets constructor name of an object
302
* @param object - Object to get constructor name from
303
* @returns Constructor name string
304
*/
305
function getObjectName(object: Object): string;
306
307
/**
308
* Generates inline preview for a JavaScript object based on type and value
309
* @param type - Type string from getType()
310
* @param object - Original object for reference
311
* @param value - String representation of the value
312
* @returns Formatted preview string
313
*/
314
function getValuePreview(type: string, object: Object, value: string): string;
315
316
/**
317
* Generates inline preview for any JavaScript object
318
* @param object - Object to generate preview for
319
* @returns Preview string representation
320
*/
321
function getPreview(object: any): string;
322
323
/**
324
* Generates a prefixed CSS class name for styling
325
* @param className - Base class name
326
* @returns Prefixed class name (json-formatter-{className})
327
*/
328
function cssClass(className: string): string;
329
330
/**
331
* Creates a new DOM element with given type and class
332
* @param type - HTML element type (e.g., 'div', 'span')
333
* @param className - Optional CSS class name (gets prefixed)
334
* @param content - Optional content (Element or string)
335
* @returns Created DOM Element
336
*/
337
function createElement(
338
type: string,
339
className?: string,
340
content?: Element | string
341
): Element;
342
```
343
344
**Usage Examples:**
345
346
```typescript
347
import { getType, isObject, getPreview, cssClass, createElement } from "json-formatter-js";
348
349
// Type checking
350
const valueType = getType({ foo: "bar" }); // "object"
351
const isObj = isObject([]); // true (arrays are objects)
352
353
// Preview generation
354
const preview = getPreview([1, 2, 3]); // "Array[3]"
355
356
// CSS class generation
357
const className = cssClass("value"); // "json-formatter-value"
358
359
// DOM element creation
360
const element = createElement("div", "container", "Hello World");
361
// Creates: <div class="json-formatter-container">Hello World</div>
362
```
363
364
## Types
365
366
```typescript { .api }
367
/**
368
* Configuration interface for JSONFormatter behavior and appearance
369
*/
370
interface JSONFormatterConfiguration {
371
hoverPreviewEnabled?: boolean;
372
hoverPreviewArrayCount?: number;
373
hoverPreviewFieldCount?: number;
374
animateOpen?: boolean;
375
animateClose?: boolean;
376
theme?: string;
377
useToJSON?: boolean;
378
sortPropertiesBy?: (a: string, b: string) => number;
379
maxArrayItems?: number;
380
exposePath?: boolean;
381
}
382
383
/**
384
* Default configuration values
385
*/
386
const defaultConfig: JSONFormatterConfiguration = {
387
hoverPreviewEnabled: false,
388
hoverPreviewArrayCount: 100,
389
hoverPreviewFieldCount: 5,
390
animateOpen: true,
391
animateClose: true,
392
theme: null,
393
useToJSON: true,
394
sortPropertiesBy: null,
395
maxArrayItems: 100,
396
exposePath: false
397
};
398
```