0
# JSON Serialization
1
2
Serialization system for converting reflections to/from JSON format, enabling data exchange, custom processing workflows, and integration with external tools.
3
4
## Capabilities
5
6
### Serializer Class
7
8
Main serializer that converts TypeDoc reflections to JSON format for storage, transmission, or external processing.
9
10
```typescript { .api }
11
/**
12
* Serializer converts reflections to JSON format
13
*/
14
class Serializer extends AbstractComponent<Application, SerializerEvents> {
15
/** Application instance */
16
readonly application: Application;
17
18
/**
19
* Convert project reflection to JSON object
20
* @param project - Project reflection to serialize
21
* @param out - Output directory path for relative path resolution
22
* @returns JSON representation of project
23
*/
24
projectToObject(project: ProjectReflection, out: string): JSONOutput.ProjectReflection;
25
26
/**
27
* Convert any value to JSON-serializable object
28
* @param value - Value to serialize
29
* @returns JSON-serializable representation
30
*/
31
toObject(value: unknown): unknown;
32
33
/**
34
* Add custom serializer component
35
* @param name - Component name
36
* @param component - Serializer component
37
*/
38
addComponent(name: string, component: SerializerComponent): void;
39
40
/**
41
* Remove serializer component
42
* @param name - Component name to remove
43
*/
44
removeComponent(name: string): void;
45
46
/**
47
* Get serializer component
48
* @param name - Component name
49
* @returns Serializer component or undefined
50
*/
51
getComponent(name: string): SerializerComponent | undefined;
52
}
53
```
54
55
**Usage Examples:**
56
57
```typescript
58
import { Application, Serializer } from "typedoc";
59
60
const app = await Application.bootstrap({
61
entryPoints: ["src/index.ts"],
62
});
63
64
const project = await app.convert();
65
if (project) {
66
// Serialize project to JSON
67
const serializer = app.serializer;
68
const jsonProject = serializer.projectToObject(project, "docs");
69
70
// Save to file
71
await writeFile("docs/api.json", JSON.stringify(jsonProject, null, 2));
72
73
// Serialize individual reflection
74
const mainModule = project.children?.[0];
75
if (mainModule) {
76
const jsonModule = serializer.toObject(mainModule);
77
console.log("Serialized module:", jsonModule);
78
}
79
}
80
```
81
82
### Deserializer Class
83
84
Deserializer that reconstructs TypeDoc reflections from JSON format for loading saved documentation data.
85
86
```typescript { .api }
87
/**
88
* Deserializer reconstructs reflections from JSON format
89
*/
90
class Deserializer {
91
/** Application instance */
92
readonly application: Application;
93
/** Deserializer components */
94
readonly components: Map<string, DeserializerComponent>;
95
96
/**
97
* Create deserializer instance
98
* @param application - Application instance
99
*/
100
constructor(application: Application);
101
102
/**
103
* Revive project reflection from JSON
104
* @param project - JSON project data
105
* @param name - Optional project name override
106
* @returns Reconstructed project reflection
107
*/
108
reviveProject(project: JSONOutput.ProjectReflection, name?: string): ProjectReflection;
109
110
/**
111
* Revive any object from JSON representation
112
* @param obj - JSON object to revive
113
* @param root - Root object for context
114
* @returns Revived object
115
*/
116
revive<T>(obj: any, root: T): T;
117
118
/**
119
* Add custom deserializer component
120
* @param name - Component name
121
* @param component - Deserializer component
122
*/
123
addComponent(name: string, component: DeserializerComponent): void;
124
125
/**
126
* Remove deserializer component
127
* @param name - Component name to remove
128
*/
129
removeComponent(name: string): void;
130
131
/**
132
* Get deserializer component
133
* @param name - Component name
134
* @returns Deserializer component or undefined
135
*/
136
getComponent(name: string): DeserializerComponent | undefined;
137
}
138
```
139
140
**Usage Examples:**
141
142
```typescript
143
import { Application, Deserializer } from "typedoc";
144
import { readFile } from "fs/promises";
145
146
const app = await Application.bootstrap();
147
148
// Load JSON data
149
const jsonData = await readFile("docs/api.json", "utf8");
150
const jsonProject = JSON.parse(jsonData);
151
152
// Deserialize back to reflections
153
const deserializer = new Deserializer(app);
154
const project = deserializer.reviveProject(jsonProject);
155
156
console.log(`Revived project: ${project.name}`);
157
console.log(`Modules: ${project.children?.length}`);
158
159
// Use revived project for rendering or analysis
160
await app.generateDocs(project, "revived-docs");
161
```
162
163
### Serialization Events
164
165
Events fired during serialization process for customization and plugin integration.
166
167
```typescript { .api }
168
/**
169
* Event fired during serialization of individual objects
170
*/
171
class SerializeEvent extends Event {
172
/** Object being serialized */
173
readonly obj: unknown;
174
/** JSON output being built */
175
output: unknown;
176
177
/**
178
* Create serialize event
179
* @param name - Event name
180
* @param obj - Object being serialized
181
* @param output - JSON output
182
*/
183
constructor(name: string, obj: unknown, output: unknown);
184
}
185
186
/**
187
* Events fired during serialization
188
*/
189
interface SerializerEvents {
190
/** Begin serialization */
191
BEGIN: [SerializeEvent];
192
/** End serialization */
193
END: [SerializeEvent];
194
/** Serialize specific object */
195
SERIALIZE: [SerializeEvent];
196
}
197
```
198
199
### Serialization Components
200
201
Component system for extending serialization behavior for custom types and data.
202
203
```typescript { .api }
204
/**
205
* Component interface for custom serialization
206
*/
207
interface SerializerComponent {
208
/**
209
* Serialize object to JSON representation
210
* @param instance - Object instance to serialize
211
* @param obj - Current JSON object being built
212
* @returns Modified JSON object
213
*/
214
serializeObject(instance: unknown, obj: any): any;
215
216
/**
217
* Serialize group of objects
218
* @param instance - Object instance
219
* @param obj - JSON object
220
* @returns Modified JSON object
221
*/
222
serializeGroup?(instance: unknown, obj: any): any;
223
224
/**
225
* Serialize group member
226
* @param instance - Object instance
227
* @param obj - JSON object
228
* @returns Modified JSON object
229
*/
230
serializeGroupMember?(instance: unknown, obj: any): any;
231
}
232
233
/**
234
* Component interface for custom deserialization
235
*/
236
interface DeserializerComponent {
237
/**
238
* Deserialize object from JSON representation
239
* @param instance - Object instance being built
240
* @param obj - JSON data
241
* @returns Modified object instance
242
*/
243
deserializeObject(instance: unknown, obj: any): unknown;
244
245
/**
246
* Deserialize group of objects
247
* @param instance - Object instance
248
* @param obj - JSON data
249
* @returns Modified object instance
250
*/
251
deserializeGroup?(instance: unknown, obj: any): unknown;
252
253
/**
254
* Deserialize group member
255
* @param instance - Object instance
256
* @param obj - JSON data
257
* @returns Modified object instance
258
*/
259
deserializeGroupMember?(instance: unknown, obj: any): unknown;
260
}
261
```
262
263
**Usage Examples:**
264
265
```typescript
266
import { SerializerComponent, DeserializerComponent } from "typedoc";
267
268
// Custom serializer component for adding metadata
269
class MetadataSerializerComponent implements SerializerComponent {
270
serializeObject(instance: unknown, obj: any): any {
271
// Add custom metadata to all reflections
272
if (instance instanceof Reflection) {
273
obj.customMetadata = {
274
serializationTime: Date.now(),
275
version: "1.0.0",
276
customId: `custom-${instance.id}`,
277
};
278
}
279
return obj;
280
}
281
}
282
283
// Custom deserializer component for processing metadata
284
class MetadataDeserializerComponent implements DeserializerComponent {
285
deserializeObject(instance: unknown, obj: any): unknown {
286
if (obj.customMetadata && instance instanceof Reflection) {
287
// Process custom metadata
288
console.log(`Deserializing ${instance.name} from ${obj.customMetadata.serializationTime}`);
289
}
290
return instance;
291
}
292
}
293
294
// Register components
295
app.serializer.addComponent("metadata", new MetadataSerializerComponent());
296
297
const deserializer = new Deserializer(app);
298
deserializer.addComponent("metadata", new MetadataDeserializerComponent());
299
```
300
301
### Deserializable Interface
302
303
Interface for objects that can customize their deserialization behavior.
304
305
```typescript { .api }
306
/**
307
* Interface for objects that support custom deserialization
308
*/
309
interface Deserializable {
310
/**
311
* Custom deserialization logic
312
* @param de - Deserializer instance
313
* @param obj - JSON object data
314
*/
315
fromObject(de: Deserializer, obj: any): void;
316
}
317
```
318
319
## JSON Output Schema
320
321
Complete schema definitions for TypeDoc's JSON output format.
322
323
### Core JSON Types
324
325
```typescript { .api }
326
namespace JSONOutput {
327
/**
328
* Base JSON reflection interface
329
*/
330
interface Reflection {
331
/** Reflection ID */
332
id: number;
333
/** Reflection name */
334
name: string;
335
/** Reflection kind */
336
kind: ReflectionKind;
337
/** Reflection flags */
338
flags: ReflectionFlag;
339
/** Comment data */
340
comment?: Comment;
341
/** Source references */
342
sources?: SourceReference[];
343
/** Groups */
344
groups?: ReflectionGroup[];
345
/** Categories */
346
categories?: ReflectionCategory[];
347
}
348
349
/**
350
* JSON project reflection
351
*/
352
interface ProjectReflection extends Reflection {
353
/** Package version */
354
packageVersion?: string;
355
/** README content */
356
readme?: string;
357
/** Changelog content */
358
changelog?: string;
359
/** Child reflections */
360
children?: DeclarationReflection[];
361
/** Groups organizing children */
362
groups?: ReflectionGroup[];
363
/** Categories organizing children */
364
categories?: ReflectionCategory[];
365
/** Symbol ID mappings */
366
symbolIdMap?: Record<string, number>;
367
}
368
369
/**
370
* JSON declaration reflection
371
*/
372
interface DeclarationReflection extends Reflection {
373
/** Type information */
374
type?: SomeType;
375
/** Default value */
376
defaultValue?: string;
377
/** Overwrites information */
378
overwrites?: ReferenceType;
379
/** Inherited from information */
380
inheritedFrom?: ReferenceType;
381
/** Implementation information */
382
implementationOf?: ReferenceType;
383
/** Extended types */
384
extendedTypes?: SomeType[];
385
/** Extended by types */
386
extendedBy?: ReferenceType[];
387
/** Implemented types */
388
implementedTypes?: SomeType[];
389
/** Implemented by types */
390
implementedBy?: ReferenceType[];
391
/** Type parameters */
392
typeParameters?: TypeParameterReflection[];
393
/** Signatures */
394
signatures?: SignatureReflection[];
395
/** Index signature */
396
indexSignature?: SignatureReflection;
397
/** Get signature */
398
getSignature?: SignatureReflection;
399
/** Set signature */
400
setSignature?: SignatureReflection;
401
/** Child reflections */
402
children?: DeclarationReflection[];
403
/** Variant information */
404
variant?: ReflectionVariant;
405
}
406
407
/**
408
* JSON signature reflection
409
*/
410
interface SignatureReflection extends Reflection {
411
/** Parameters */
412
parameters?: ParameterReflection[];
413
/** Return type */
414
type?: SomeType;
415
/** Type parameters */
416
typeParameters?: TypeParameterReflection[];
417
/** Overwrites information */
418
overwrites?: ReferenceType;
419
/** Inherited from information */
420
inheritedFrom?: ReferenceType;
421
/** Implementation information */
422
implementationOf?: ReferenceType;
423
}
424
425
/**
426
* JSON parameter reflection
427
*/
428
interface ParameterReflection extends Reflection {
429
/** Parameter type */
430
type?: SomeType;
431
/** Default value */
432
defaultValue?: string;
433
/** Rest parameter flag */
434
rest?: boolean;
435
/** Optional parameter flag */
436
optional?: boolean;
437
}
438
439
/**
440
* JSON type parameter reflection
441
*/
442
interface TypeParameterReflection extends Reflection {
443
/** Type constraint */
444
type?: SomeType;
445
/** Default type */
446
default?: SomeType;
447
/** Constraint type */
448
constraint?: SomeType;
449
}
450
}
451
```
452
453
### JSON Type System
454
455
```typescript { .api }
456
namespace JSONOutput {
457
/**
458
* Union of all possible JSON type representations
459
*/
460
type SomeType =
461
| ArrayType
462
| ConditionalType
463
| IndexedAccessType
464
| InferredType
465
| IntersectionType
466
| IntrinsicType
467
| LiteralType
468
| MappedType
469
| NamedTupleMemberType
470
| OptionalType
471
| PredicateType
472
| QueryType
473
| ReferenceType
474
| ReflectionType
475
| RestType
476
| TemplateStringType
477
| TupleType
478
| TypeOperatorType
479
| UnionType
480
| UnknownType;
481
482
/**
483
* JSON intrinsic type
484
*/
485
interface IntrinsicType {
486
type: "intrinsic";
487
name: string;
488
}
489
490
/**
491
* JSON literal type
492
*/
493
interface LiteralType {
494
type: "literal";
495
value?: string | number | boolean | null | bigint;
496
}
497
498
/**
499
* JSON reference type
500
*/
501
interface ReferenceType {
502
type: "reference";
503
/** Reference target name */
504
name: string;
505
/** Type arguments */
506
typeArguments?: SomeType[];
507
/** Referenced reflection ID */
508
target?: number;
509
/** External package */
510
package?: string;
511
/** Qualified name */
512
qualifiedName?: string;
513
}
514
515
/**
516
* JSON array type
517
*/
518
interface ArrayType {
519
type: "array";
520
/** Element type */
521
elementType: SomeType;
522
}
523
524
/**
525
* JSON union type
526
*/
527
interface UnionType {
528
type: "union";
529
/** Union member types */
530
types: SomeType[];
531
}
532
533
/**
534
* JSON intersection type
535
*/
536
interface IntersectionType {
537
type: "intersection";
538
/** Intersection member types */
539
types: SomeType[];
540
}
541
542
/**
543
* JSON conditional type
544
*/
545
interface ConditionalType {
546
type: "conditional";
547
/** Check type */
548
checkType: SomeType;
549
/** Extends type */
550
extendsType: SomeType;
551
/** True type */
552
trueType: SomeType;
553
/** False type */
554
falseType: SomeType;
555
}
556
557
/**
558
* JSON tuple type
559
*/
560
interface TupleType {
561
type: "tuple";
562
/** Tuple element types */
563
elements: SomeType[];
564
}
565
566
/**
567
* JSON mapped type
568
*/
569
interface MappedType {
570
type: "mapped";
571
/** Parameter name */
572
parameter: string;
573
/** Parameter type */
574
parameterType: SomeType;
575
/** Template type */
576
templateType: SomeType;
577
/** Readonly modifier */
578
readonlyModifier?: "+" | "-";
579
/** Optional modifier */
580
optionalModifier?: "+" | "-";
581
/** Name type */
582
nameType?: SomeType;
583
}
584
585
/**
586
* JSON template literal type
587
*/
588
interface TemplateStringType {
589
type: "templateString";
590
/** Template head */
591
head: string;
592
/** Template tail parts */
593
tail: [SomeType, string][];
594
}
595
}
596
```
597
598
### JSON Utility Types
599
600
```typescript { .api }
601
namespace JSONOutput {
602
/**
603
* JSON comment representation
604
*/
605
interface Comment {
606
/** Summary parts */
607
summary: CommentDisplayPart[];
608
/** Block tags */
609
blockTags?: CommentTag[];
610
/** Modifier tags */
611
modifierTags?: string[];
612
}
613
614
/**
615
* JSON comment display part
616
*/
617
interface CommentDisplayPart {
618
/** Part kind */
619
kind: string;
620
/** Text content */
621
text: string;
622
/** Link target */
623
target?: number | string;
624
}
625
626
/**
627
* JSON comment tag
628
*/
629
interface CommentTag {
630
/** Tag name */
631
tag: string;
632
/** Tag content */
633
content: CommentDisplayPart[];
634
/** Parameter name for @param tags */
635
name?: string;
636
}
637
638
/**
639
* JSON source reference
640
*/
641
interface SourceReference {
642
/** File name */
643
fileName: string;
644
/** Line number */
645
line: number;
646
/** Character position */
647
character: number;
648
/** Source URL */
649
url?: string;
650
}
651
652
/**
653
* JSON reflection group
654
*/
655
interface ReflectionGroup {
656
/** Group title */
657
title: string;
658
/** Child reflection IDs */
659
children: number[];
660
/** Categories */
661
categories?: ReflectionCategory[];
662
}
663
664
/**
665
* JSON reflection category
666
*/
667
interface ReflectionCategory {
668
/** Category title */
669
title: string;
670
/** Child reflection IDs */
671
children: number[];
672
}
673
}
674
```
675
676
## Advanced Usage
677
678
### Custom JSON Processing
679
680
```typescript
681
import { Serializer, JSONOutput } from "typedoc";
682
683
// Custom JSON post-processing
684
function processJsonOutput(jsonProject: JSONOutput.ProjectReflection): JSONOutput.ProjectReflection {
685
// Add custom metadata
686
const processed = {
687
...jsonProject,
688
metadata: {
689
generatedAt: new Date().toISOString(),
690
version: "1.0.0",
691
processingFlags: ["minified", "optimized"],
692
},
693
};
694
695
// Process all children recursively
696
if (processed.children) {
697
processed.children = processed.children.map(child => ({
698
...child,
699
processedAt: Date.now(),
700
}));
701
}
702
703
return processed;
704
}
705
706
const project = await app.convert();
707
if (project) {
708
let jsonProject = app.serializer.projectToObject(project, "docs");
709
jsonProject = processJsonOutput(jsonProject);
710
711
await writeFile("docs/processed-api.json", JSON.stringify(jsonProject, null, 2));
712
}
713
```
714
715
### Streaming Serialization
716
717
```typescript
718
import { Serializer } from "typedoc";
719
import { createWriteStream } from "fs";
720
721
// Stream large JSON output
722
async function streamSerializeProject(project: ProjectReflection, outputPath: string) {
723
const stream = createWriteStream(outputPath);
724
const serializer = app.serializer;
725
726
stream.write('{"project":');
727
728
// Serialize in chunks
729
const jsonProject = serializer.projectToObject(project, path.dirname(outputPath));
730
stream.write(JSON.stringify(jsonProject));
731
732
stream.write('}');
733
stream.end();
734
735
return new Promise<void>((resolve, reject) => {
736
stream.on('finish', resolve);
737
stream.on('error', reject);
738
});
739
}
740
```
741
742
## Error Handling
743
744
The serialization system handles various error conditions:
745
746
- **Memory Limits**: Large projects, deep object nesting, circular references
747
- **Type Conversion**: Complex type structures, generic constraints, recursive types
748
- **File I/O**: Disk space, permissions, concurrent access, corruption
749
- **Data Integrity**: Missing references, broken links, invalid IDs
750
- **Version Compatibility**: Schema changes, deprecated fields, migration issues
751
752
All serialization errors include context about the failing object and operation for debugging.