0
# JSON Utilities
1
2
Comprehensive JSON handling utilities for both virtual tree operations and filesystem I/O. These utilities provide consistent JSON parsing, serialization, and file manipulation with support for comments and custom formatting options.
3
4
## Capabilities
5
6
### Tree-based JSON Operations
7
8
Functions for working with JSON files in the virtual Tree filesystem.
9
10
```typescript { .api }
11
/**
12
* Read and parse JSON from the virtual tree
13
* @template T - Expected JSON structure type
14
* @param tree - Virtual file system tree
15
* @param path - Path to the JSON file
16
* @returns Parsed JSON object
17
*/
18
function readJson<T = any>(tree: Tree, path: string): T;
19
20
/**
21
* Serialize and write JSON to the virtual tree
22
* @template T - JSON data type
23
* @param tree - Virtual file system tree
24
* @param path - Path where to write the JSON file
25
* @param value - Object to serialize to JSON
26
* @param options - Optional serialization options
27
*/
28
function writeJson<T = any>(
29
tree: Tree,
30
path: string,
31
value: T,
32
options?: JsonSerializeOptions
33
): void;
34
35
/**
36
* Update JSON file using an updater function
37
* @template T - Current JSON structure type
38
* @template U - Updated JSON structure type
39
* @param tree - Virtual file system tree
40
* @param path - Path to the JSON file
41
* @param updater - Function to transform the JSON
42
* @param options - Optional serialization options
43
* @returns The updated JSON value
44
*/
45
function updateJson<T = any, U = T>(
46
tree: Tree,
47
path: string,
48
updater: (json: T) => U,
49
options?: JsonSerializeOptions
50
): U;
51
```
52
53
**Usage Examples:**
54
55
```typescript
56
import { Tree, readJson, writeJson, updateJson } from "@nrwl/devkit";
57
58
function manageJsonFiles(tree: Tree) {
59
// Read package.json
60
const packageJson = readJson(tree, 'package.json');
61
console.log('Package name:', packageJson.name);
62
63
// Write new JSON file
64
const newConfig = {
65
version: '1.0.0',
66
features: ['feature1', 'feature2'],
67
settings: {
68
debug: true,
69
timeout: 30000
70
}
71
};
72
writeJson(tree, 'config/app.json', newConfig);
73
74
// Update existing JSON file
75
updateJson(tree, 'package.json', (json) => {
76
return {
77
...json,
78
scripts: {
79
...json.scripts,
80
'custom-build': 'nx build --prod'
81
}
82
};
83
});
84
}
85
```
86
87
### File System JSON Operations
88
89
Functions for direct JSON file I/O on the filesystem.
90
91
```typescript { .api }
92
/**
93
* Read and parse JSON file from filesystem
94
* @template T - Expected JSON structure type
95
* @param path - File path to read
96
* @param options - Optional parse options
97
* @returns Parsed JSON object
98
*/
99
function readJsonFile<T = any>(path: string, options?: JsonParseOptions): T;
100
101
/**
102
* Serialize and write JSON file to filesystem
103
* @template T - JSON data type
104
* @param path - File path to write
105
* @param data - Object to serialize to JSON
106
* @param options - Optional serialization options
107
*/
108
function writeJsonFile<T = any>(
109
path: string,
110
data: T,
111
options?: JsonSerializeOptions
112
): void;
113
```
114
115
**Usage Examples:**
116
117
```typescript
118
import { readJsonFile, writeJsonFile } from "@nrwl/devkit";
119
120
function handleJsonFiles() {
121
// Read JSON file from disk
122
const config = readJsonFile('config/settings.json');
123
124
// Modify and write back
125
config.lastUpdated = new Date().toISOString();
126
writeJsonFile('config/settings.json', config, {
127
spaces: 2
128
});
129
130
// Read with error handling
131
try {
132
const userConfig = readJsonFile('config/user.json');
133
console.log('User config loaded:', userConfig);
134
} catch (error) {
135
console.warn('User config not found, using defaults');
136
}
137
}
138
```
139
140
### JSON Parsing and Serialization
141
142
Low-level JSON processing functions with advanced options.
143
144
```typescript { .api }
145
/**
146
* Parse JSON string with support for comments and custom options
147
* @template T - Expected JSON structure type
148
* @param input - JSON string to parse
149
* @param options - Parse options
150
* @returns Parsed JSON object
151
*/
152
function parseJson<T = any>(input: string, options?: JsonParseOptions): T;
153
154
/**
155
* Serialize object to JSON string with formatting options
156
* @template T - Object type to serialize
157
* @param input - Object to serialize
158
* @param options - Serialization options
159
* @returns Formatted JSON string
160
*/
161
function serializeJson<T = any>(input: T, options?: JsonSerializeOptions): string;
162
163
/**
164
* Remove comments from JSON string
165
* @param text - JSON string with comments
166
* @returns JSON string without comments
167
*/
168
function stripJsonComments(text: string): string;
169
```
170
171
**Usage Examples:**
172
173
```typescript
174
import {
175
parseJson,
176
serializeJson,
177
stripJsonComments,
178
JsonParseOptions
179
} from "@nrwl/devkit";
180
181
function processJsonData() {
182
// Parse JSON with comments
183
const jsonWithComments = `
184
{
185
// This is a comment
186
"name": "my-app",
187
"version": "1.0.0",
188
/* Multi-line comment */
189
"dependencies": {}
190
}
191
`;
192
193
const config = parseJson(jsonWithComments, {
194
allowTrailingComma: true,
195
disallowComments: false
196
});
197
198
// Serialize with custom formatting
199
const formatted = serializeJson(config, {
200
spaces: 4,
201
quote: '"'
202
});
203
204
console.log('Formatted JSON:', formatted);
205
206
// Strip comments manually
207
const withoutComments = stripJsonComments(jsonWithComments);
208
console.log('No comments:', withoutComments);
209
}
210
```
211
212
### JSON Options and Types
213
214
Configuration interfaces for JSON operations.
215
216
```typescript { .api }
217
/**
218
* Options for JSON parsing
219
*/
220
interface JsonParseOptions {
221
/** Whether to expect an array at the root */
222
expectComments?: boolean;
223
/** Whether to allow trailing commas */
224
allowTrailingComma?: boolean;
225
/** Whether to disallow comments */
226
disallowComments?: boolean;
227
}
228
229
/**
230
* Options for JSON serialization
231
*/
232
interface JsonSerializeOptions {
233
/** Number of spaces for indentation or '\t' for tabs */
234
spaces?: number | string;
235
/** Quote character to use */
236
quote?: '"' | "'";
237
/** Whether to quote property names */
238
quoteNames?: boolean;
239
/** Custom replacer function */
240
replacer?: (key: string, value: any) => any;
241
}
242
```
243
244
**Usage Examples:**
245
246
```typescript
247
import {
248
JsonParseOptions,
249
JsonSerializeOptions,
250
parseJson,
251
serializeJson
252
} from "@nrwl/devkit";
253
254
function customJsonHandling() {
255
const parseOptions: JsonParseOptions = {
256
allowTrailingComma: true,
257
disallowComments: false
258
};
259
260
const serializeOptions: JsonSerializeOptions = {
261
spaces: 2,
262
quote: '"',
263
replacer: (key, value) => {
264
// Don't serialize internal properties
265
if (key.startsWith('_')) return undefined;
266
return value;
267
}
268
};
269
270
const data = {
271
name: 'test',
272
_internal: 'hidden',
273
values: [1, 2, 3]
274
};
275
276
const jsonString = serializeJson(data, serializeOptions);
277
console.log('Serialized:', jsonString);
278
// Output: { "name": "test", "values": [1, 2, 3] }
279
280
const parsed = parseJson(jsonString, parseOptions);
281
console.log('Parsed:', parsed);
282
}
283
```
284
285
### Advanced JSON Operations
286
287
Specialized functions for complex JSON manipulation scenarios.
288
289
```typescript { .api }
290
/**
291
* Deep merge JSON objects
292
* @param target - Target object to merge into
293
* @param sources - Source objects to merge from
294
* @returns Merged object
295
*/
296
function deepMergeJson<T = any>(target: T, ...sources: Partial<T>[]): T;
297
298
/**
299
* Compare two JSON objects for structural equality
300
* @param a - First object
301
* @param b - Second object
302
* @returns Whether objects are structurally equal
303
*/
304
function isJsonEqual(a: any, b: any): boolean;
305
306
/**
307
* Get JSON schema for an object
308
* @param obj - Object to generate schema for
309
* @returns JSON schema object
310
*/
311
function getJsonSchema(obj: any): Record<string, any>;
312
```
313
314
**Usage Examples:**
315
316
```typescript
317
import { deepMergeJson, isJsonEqual } from "@nrwl/devkit";
318
319
function advancedJsonOperations() {
320
const baseConfig = {
321
name: 'app',
322
features: ['auth'],
323
settings: {
324
theme: 'dark',
325
timeout: 5000
326
}
327
};
328
329
const overrides = {
330
features: ['auth', 'notifications'],
331
settings: {
332
timeout: 10000,
333
debug: true
334
}
335
};
336
337
// Deep merge configurations
338
const merged = deepMergeJson(baseConfig, overrides);
339
console.log('Merged config:', merged);
340
// Result: {
341
// name: 'app',
342
// features: ['auth', 'notifications'],
343
// settings: { theme: 'dark', timeout: 10000, debug: true }
344
// }
345
346
// Compare configurations
347
const isEqual = isJsonEqual(baseConfig, merged);
348
console.log('Configs equal:', isEqual); // false
349
}
350
```