0
# JSON Operations
1
2
Safe JSON parsing and file I/O operations with proper error handling, directory creation, and configurable formatting options for robust data persistence and processing.
3
4
## Capabilities
5
6
### Strict JSON Parsing
7
8
Strict JSON parsing that ensures the result is an object type.
9
10
```typescript { .api }
11
/**
12
* Strict JSON parse that validates result is an object
13
* @param content - JSON string to parse
14
* @returns Parsed object (throws if not an object)
15
*/
16
function strictJSONParse<T extends object = object>(content: string): T;
17
```
18
19
**Usage Examples:**
20
21
```typescript
22
import { strictJSONParse } from "utility";
23
24
// Valid object parsing
25
const user = strictJSONParse<{name: string, age: number}>('{"name": "Alice", "age": 30}');
26
// Result: { name: "Alice", age: 30 }
27
28
// Array parsing (throws error)
29
try {
30
const invalid = strictJSONParse('[1, 2, 3]');
31
} catch (error) {
32
// Error: JSON string is not object
33
}
34
35
// Primitive parsing (throws error)
36
try {
37
const invalid = strictJSONParse('"string"');
38
} catch (error) {
39
// Error: JSON string is not object
40
}
41
```
42
43
### Synchronous JSON File Operations
44
45
Synchronous JSON file reading and writing with automatic directory creation.
46
47
```typescript { .api }
48
/**
49
* Read JSON file synchronously
50
* @param filepath - Path to JSON file
51
* @returns Parsed JSON content
52
*/
53
function readJSONSync<T = any>(filepath: string): T;
54
55
/**
56
* Write JSON file synchronously with directory creation
57
* @param filepath - Path to write JSON file
58
* @param content - Content to write (string or object)
59
* @param options - Formatting options
60
*/
61
function writeJSONSync(filepath: string, content: string | object, options?: JSONStringifyOptions): void;
62
63
interface JSONStringifyOptions {
64
space?: number | string;
65
replacer?: (this: any, key: string, value: any) => any;
66
}
67
```
68
69
**Usage Examples:**
70
71
```typescript
72
import { readJSONSync, writeJSONSync } from "utility";
73
74
// Read JSON file
75
const config = readJSONSync<{port: number, host: string}>('./config.json');
76
// Result: parsed JSON object
77
78
// Write object to JSON file
79
writeJSONSync('./output.json', {
80
name: 'test',
81
value: 42,
82
timestamp: new Date().toISOString()
83
});
84
85
// Write with custom formatting
86
writeJSONSync('./formatted.json', { data: 'value' }, {
87
space: 4,
88
replacer: (key, value) => typeof value === 'string' ? value.toUpperCase() : value
89
});
90
91
// Write JSON string directly
92
writeJSONSync('./direct.json', '{"already": "json"}');
93
94
// Automatic directory creation
95
writeJSONSync('./nested/deep/path/file.json', { created: true });
96
```
97
98
### Asynchronous JSON File Operations
99
100
Asynchronous JSON file reading and writing with promise-based API.
101
102
```typescript { .api }
103
/**
104
* Read JSON file asynchronously
105
* @param filepath - Path to JSON file
106
* @returns Promise resolving to parsed JSON content
107
*/
108
function readJSON<T = any>(filepath: string): Promise<T>;
109
110
/**
111
* Write JSON file asynchronously with directory creation
112
* @param filepath - Path to write JSON file
113
* @param content - Content to write (string or object)
114
* @param options - Formatting options
115
* @returns Promise that resolves when write completes
116
*/
117
function writeJSON(filepath: string, content: string | object, options?: JSONStringifyOptions): Promise<void>;
118
```
119
120
**Usage Examples:**
121
122
```typescript
123
import { readJSON, writeJSON } from "utility";
124
125
// Read JSON file asynchronously
126
const configData = await readJSON<{database: string}>('./config.json');
127
console.log(configData.database);
128
129
// Write JSON file asynchronously
130
await writeJSON('./async-output.json', {
131
timestamp: Date.now(),
132
data: [1, 2, 3, 4, 5]
133
});
134
135
// Batch operations
136
const promises = [
137
writeJSON('./file1.json', { id: 1 }),
138
writeJSON('./file2.json', { id: 2 }),
139
writeJSON('./file3.json', { id: 3 })
140
];
141
await Promise.all(promises);
142
143
// With custom formatting
144
await writeJSON('./pretty.json', {
145
nested: {
146
data: 'value'
147
}
148
}, {
149
space: 2
150
});
151
152
// Error handling
153
try {
154
const data = await readJSON('./nonexistent.json');
155
} catch (error) {
156
console.error('File not found or invalid JSON');
157
}
158
```
159
160
### JSON Formatting Options
161
162
Configuration options for JSON stringification with custom formatting and replacement.
163
164
```typescript { .api }
165
interface JSONStringifyOptions {
166
/**
167
* A string or number for indentation (defaults to 2 spaces)
168
*/
169
space?: number | string;
170
171
/**
172
* A function that transforms results or array of property names
173
*/
174
replacer?: (this: any, key: string, value: any) => any;
175
}
176
```
177
178
**Usage Examples:**
179
180
```typescript
181
import { writeJSONSync } from "utility";
182
183
// Tab indentation
184
writeJSONSync('./tabs.json', { data: 'value' }, { space: '\t' });
185
186
// No formatting (compact)
187
writeJSONSync('./compact.json', { data: 'value' }, { space: 0 });
188
189
// Custom replacer function
190
writeJSONSync('./filtered.json', {
191
public: 'visible',
192
private: 'hidden',
193
secret: 'confidential'
194
}, {
195
space: 2,
196
replacer: (key, value) => {
197
if (key === 'secret') return undefined; // Remove secret fields
198
return value;
199
}
200
});
201
202
// Transform values
203
writeJSONSync('./transformed.json', {
204
date: new Date(),
205
number: 42.123456
206
}, {
207
space: 2,
208
replacer: (key, value) => {
209
if (value instanceof Date) return value.toISOString();
210
if (typeof value === 'number') return Math.round(value * 100) / 100;
211
return value;
212
}
213
});
214
```