json-stream-lite 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/EXAMPLES.md +1046 -0
- package/LICENSE +21 -0
- package/README.md +2 -0
- package/package.json +34 -4
- package/dist/incremental-parser.d.ts +0 -103
- package/dist/incremental-parser.js +0 -184
- package/dist/json-key-value-pair.d.ts +0 -6
- package/dist/json-key-value-pair.js +0 -8
- package/dist/json-parser.d.ts +0 -64
- package/dist/json-parser.js +0 -428
package/EXAMPLES.md
ADDED
|
@@ -0,0 +1,1046 @@
|
|
|
1
|
+
# JSON-Stream-Lite Examples
|
|
2
|
+
|
|
3
|
+
This directory contains example scripts demonstrating how to use the JSON-Stream-Lite library.
|
|
4
|
+
|
|
5
|
+
## Helper to convert string to bytes
|
|
6
|
+
|
|
7
|
+
```typescript
|
|
8
|
+
function stringToBytes(str: string): number[] {
|
|
9
|
+
return Array.from(new TextEncoder().encode(str))
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// Example 1: Parse a simple object
|
|
13
|
+
console.log('=== Example 1: Parse Simple Object ===')
|
|
14
|
+
const simpleJson = '{"name": "Alice", "age": 30, "active": true}'
|
|
15
|
+
const simpleParser = new JsonObject()
|
|
16
|
+
simpleParser.feed(...stringToBytes(simpleJson))
|
|
17
|
+
|
|
18
|
+
const simpleResult = simpleParser.read()
|
|
19
|
+
console.log('Result:', simpleResult)
|
|
20
|
+
// Output: { name: 'Alice', age: 30, active: true }
|
|
21
|
+
|
|
22
|
+
// Example 2: Parse an array
|
|
23
|
+
console.log('\n=== Example 2: Parse Array ===')
|
|
24
|
+
const arrayJson = '[1, 2, 3, 4, 5]'
|
|
25
|
+
const arrayParser = new JsonArray()
|
|
26
|
+
arrayParser.feed(...stringToBytes(arrayJson))
|
|
27
|
+
|
|
28
|
+
const arrayResult = arrayParser.read()
|
|
29
|
+
console.log('Result:', arrayResult)
|
|
30
|
+
// Output: [1, 2, 3, 4, 5]
|
|
31
|
+
|
|
32
|
+
// Example 3: Parse nested structure
|
|
33
|
+
console.log('\n=== Example 3: Parse Nested Structure ===')
|
|
34
|
+
const nestedJson =
|
|
35
|
+
'{"user": {"name": "Bob", "scores": [95, 87, 92]}, "verified": true}'
|
|
36
|
+
const nestedParser = new JsonObject()
|
|
37
|
+
nestedParser.feed(...stringToBytes(nestedJson))
|
|
38
|
+
|
|
39
|
+
const nestedResult = nestedParser.read()
|
|
40
|
+
console.log('Result:', JSON.stringify(nestedResult, null, 2))
|
|
41
|
+
|
|
42
|
+
// Example 4: Parse using JsonValue (auto-detects type)
|
|
43
|
+
console.log('\n=== Example 4: Auto-detect Type with JsonValue ===')
|
|
44
|
+
const valueParser = new JsonValue()
|
|
45
|
+
valueParser.feed(...stringToBytes('{"status": "ok"}'))
|
|
46
|
+
|
|
47
|
+
const valueEntity = valueParser.read()
|
|
48
|
+
console.log('Entity type:', valueEntity.constructor.name) // JsonObject
|
|
49
|
+
const value = valueEntity.read()
|
|
50
|
+
console.log('Result:', value)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Example 1: Stream through object members
|
|
54
|
+
|
|
55
|
+
```typescript
|
|
56
|
+
console.log('=== Example 1: Stream Object Members ===')
|
|
57
|
+
const userJson =
|
|
58
|
+
'{"id": 123, "name": "Alice", "email": "alice@example.com", "age": 30}'
|
|
59
|
+
const userParser = new JsonObject()
|
|
60
|
+
userParser.feed(...stringToBytes(userJson))
|
|
61
|
+
|
|
62
|
+
console.log('Processing members one by one:')
|
|
63
|
+
for (const [keyEntity, valueEntity] of userParser.members()) {
|
|
64
|
+
const key = keyEntity.read()
|
|
65
|
+
const value = valueEntity.read().read()
|
|
66
|
+
console.log(` ${key}: ${value} (${typeof value})`)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Example 2: Stream through array items
|
|
70
|
+
console.log('\n=== Example 2: Stream Array Items ===')
|
|
71
|
+
import { JsonArray } from 'json-stream-lite'
|
|
72
|
+
|
|
73
|
+
const numbersJson = '[10, 20, 30, 40, 50]'
|
|
74
|
+
const numbersParser = new JsonArray()
|
|
75
|
+
numbersParser.feed(...stringToBytes(numbersJson))
|
|
76
|
+
|
|
77
|
+
console.log('Processing items one by one:')
|
|
78
|
+
let sum = 0
|
|
79
|
+
for (const item of numbersParser.items()) {
|
|
80
|
+
const value = item.read() as number
|
|
81
|
+
sum += value
|
|
82
|
+
console.log(` Current value: ${value}, Running sum: ${sum}`)
|
|
83
|
+
}
|
|
84
|
+
console.log(`Final sum: ${sum}`)
|
|
85
|
+
|
|
86
|
+
// Example 3: Selective processing
|
|
87
|
+
console.log('\n=== Example 3: Selective Processing ===')
|
|
88
|
+
const dataJson =
|
|
89
|
+
'{"header": "Report", "data": [1, 2, 3, 4, 5], "footer": "End"}'
|
|
90
|
+
const dataParser = new JsonObject()
|
|
91
|
+
dataParser.feed(...stringToBytes(dataJson))
|
|
92
|
+
|
|
93
|
+
console.log('Only processing the "data" field:')
|
|
94
|
+
for (const [keyEntity, valueEntity] of dataParser.members()) {
|
|
95
|
+
const key = keyEntity.read()
|
|
96
|
+
|
|
97
|
+
if (key === 'data') {
|
|
98
|
+
const value = valueEntity.read()
|
|
99
|
+
if (value instanceof JsonArray) {
|
|
100
|
+
const items = []
|
|
101
|
+
for (const item of value.items()) {
|
|
102
|
+
items.push(item.read())
|
|
103
|
+
}
|
|
104
|
+
console.log(` Found data array with ${items.length} items:`, items)
|
|
105
|
+
}
|
|
106
|
+
} else {
|
|
107
|
+
// Skip other fields by just consuming them
|
|
108
|
+
valueEntity.consume()
|
|
109
|
+
console.log(` Skipped field: ${key}`)
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Example 4: Early termination
|
|
114
|
+
console.log('\n=== Example 4: Early Termination ===')
|
|
115
|
+
const largeJson = '{"a": 1, "b": 2, "c": 3, "target": 999, "d": 4, "e": 5}'
|
|
116
|
+
const searchParser = new JsonObject()
|
|
117
|
+
searchParser.feed(...stringToBytes(largeJson))
|
|
118
|
+
|
|
119
|
+
console.log('Searching for "target" field:')
|
|
120
|
+
for (const [keyEntity, valueEntity] of searchParser.members()) {
|
|
121
|
+
const key = keyEntity.read()
|
|
122
|
+
|
|
123
|
+
if (key === 'target') {
|
|
124
|
+
const value = valueEntity.read().read()
|
|
125
|
+
console.log(` Found target: ${value}`)
|
|
126
|
+
break // Stop processing once we found what we need
|
|
127
|
+
} else {
|
|
128
|
+
valueEntity.consume()
|
|
129
|
+
console.log(` Checked field: ${key}`)
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
console.log("Early exit - didn't process remaining fields")
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## Example 1: Flatten a simple nested object
|
|
136
|
+
|
|
137
|
+
```typescript
|
|
138
|
+
console.log('=== Example 1: Simple Nested Object ===')
|
|
139
|
+
const simpleNested = '{"user": {"name": "Alice", "age": 30}}'
|
|
140
|
+
|
|
141
|
+
console.log('Input:', simpleNested)
|
|
142
|
+
console.log('Flattened:')
|
|
143
|
+
for (const [key, value] of jsonKeyValueParser(simpleNested)) {
|
|
144
|
+
console.log(` ${key} = ${value}`)
|
|
145
|
+
}
|
|
146
|
+
// Output:
|
|
147
|
+
// user.name = Alice
|
|
148
|
+
// user.age = 30
|
|
149
|
+
|
|
150
|
+
// Example 2: Flatten object with arrays
|
|
151
|
+
console.log('\n=== Example 2: Object with Arrays ===')
|
|
152
|
+
const withArrays = '{"user": {"name": "Bob", "scores": [95, 87, 92]}}'
|
|
153
|
+
|
|
154
|
+
console.log('Input:', withArrays)
|
|
155
|
+
console.log('Flattened:')
|
|
156
|
+
for (const [key, value] of jsonKeyValueParser(withArrays)) {
|
|
157
|
+
console.log(` ${key} = ${value}`)
|
|
158
|
+
}
|
|
159
|
+
// Output:
|
|
160
|
+
// user.name = Bob
|
|
161
|
+
// user.scores[0] = 95
|
|
162
|
+
// user.scores[1] = 87
|
|
163
|
+
// user.scores[2] = 92
|
|
164
|
+
|
|
165
|
+
// Example 3: Complex nested structure
|
|
166
|
+
console.log('\n=== Example 3: Complex Nested Structure ===')
|
|
167
|
+
const complex = JSON.stringify({
|
|
168
|
+
company: {
|
|
169
|
+
name: 'TechCorp',
|
|
170
|
+
departments: [
|
|
171
|
+
{
|
|
172
|
+
name: 'Engineering',
|
|
173
|
+
employees: [
|
|
174
|
+
{ id: 1, name: 'Alice' },
|
|
175
|
+
{ id: 2, name: 'Bob' },
|
|
176
|
+
],
|
|
177
|
+
},
|
|
178
|
+
],
|
|
179
|
+
},
|
|
180
|
+
})
|
|
181
|
+
|
|
182
|
+
console.log('Input:', complex)
|
|
183
|
+
console.log('Flattened:')
|
|
184
|
+
for (const [key, value] of jsonKeyValueParser(complex)) {
|
|
185
|
+
console.log(` ${key} = ${value}`)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Example 4: Extract specific values
|
|
189
|
+
console.log('\n=== Example 4: Extract Specific Values ===')
|
|
190
|
+
const config = JSON.stringify({
|
|
191
|
+
database: {
|
|
192
|
+
host: 'localhost',
|
|
193
|
+
port: 5432,
|
|
194
|
+
credentials: {
|
|
195
|
+
username: 'admin',
|
|
196
|
+
password: 'secret123',
|
|
197
|
+
},
|
|
198
|
+
},
|
|
199
|
+
cache: {
|
|
200
|
+
enabled: true,
|
|
201
|
+
ttl: 3600,
|
|
202
|
+
},
|
|
203
|
+
})
|
|
204
|
+
|
|
205
|
+
console.log('Extracting only database-related configs:')
|
|
206
|
+
for (const [key, value] of jsonKeyValueParser(config)) {
|
|
207
|
+
if (key.startsWith('database.')) {
|
|
208
|
+
console.log(` ${key} = ${value}`)
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Example 5: Build a flat object
|
|
213
|
+
console.log('\n=== Example 5: Build Flat Object from JSON ===')
|
|
214
|
+
const source = '{"a": {"b": {"c": 1}}, "x": {"y": 2}}'
|
|
215
|
+
const flatObject: Record<string, any> = {}
|
|
216
|
+
|
|
217
|
+
for (const [key, value] of jsonKeyValueParser(source)) {
|
|
218
|
+
flatObject[key] = value
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
console.log('Original:', source)
|
|
222
|
+
console.log('Flat object:', flatObject)
|
|
223
|
+
console.log('Access nested value:', flatObject['a.b.c']) // 1
|
|
224
|
+
|
|
225
|
+
// Example 6: Array-only structure
|
|
226
|
+
console.log('\n=== Example 6: Array Structure ===')
|
|
227
|
+
const arrayStructure = '[[1, 2], [3, 4], [5, 6]]'
|
|
228
|
+
|
|
229
|
+
console.log('Input:', arrayStructure)
|
|
230
|
+
console.log('Flattened:')
|
|
231
|
+
for (const [key, value] of jsonKeyValueParser(arrayStructure)) {
|
|
232
|
+
console.log(` ${key} = ${value}`)
|
|
233
|
+
}
|
|
234
|
+
// Output:
|
|
235
|
+
// [0][0] = 1
|
|
236
|
+
// [0][1] = 2
|
|
237
|
+
// [1][0] = 3
|
|
238
|
+
// [1][1] = 4
|
|
239
|
+
// [2][0] = 5
|
|
240
|
+
// [2][1] = 6
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
## Helper to simulate an async byte stream
|
|
244
|
+
|
|
245
|
+
```typescript
|
|
246
|
+
async function* createAsyncByteStream(
|
|
247
|
+
json: string,
|
|
248
|
+
chunkSize: number = 10,
|
|
249
|
+
): AsyncGenerator<number> {
|
|
250
|
+
const bytes = new TextEncoder().encode(json)
|
|
251
|
+
|
|
252
|
+
for (let i = 0; i < bytes.length; i += chunkSize) {
|
|
253
|
+
// Simulate network delay
|
|
254
|
+
await new Promise((resolve) => setTimeout(resolve, 10))
|
|
255
|
+
|
|
256
|
+
const chunk = bytes.slice(i, i + chunkSize)
|
|
257
|
+
yield* chunk
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// Example 1: Parse object from async stream
|
|
262
|
+
console.log('=== Example 1: Parse Object from Async Stream ===')
|
|
263
|
+
async function parseAsyncObject() {
|
|
264
|
+
const json = '{"name": "Alice", "age": 30, "city": "NYC"}'
|
|
265
|
+
const stream = createAsyncByteStream(json)
|
|
266
|
+
|
|
267
|
+
const parser = new JsonObject(stream)
|
|
268
|
+
|
|
269
|
+
console.log('Streaming members asynchronously:')
|
|
270
|
+
for await (const [keyEntity, valueEntity] of parser) {
|
|
271
|
+
const key = keyEntity.read()
|
|
272
|
+
const value = await valueEntity.readValueAsync()
|
|
273
|
+
console.log(` ${key}: ${value}`)
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
await parseAsyncObject()
|
|
278
|
+
|
|
279
|
+
// Example 2: Parse array from async stream
|
|
280
|
+
console.log('\n=== Example 2: Parse Array from Async Stream ===')
|
|
281
|
+
async function parseAsyncArray() {
|
|
282
|
+
const json = '[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]'
|
|
283
|
+
const stream = createAsyncByteStream(json, 5)
|
|
284
|
+
|
|
285
|
+
const parser = new JsonArray(stream)
|
|
286
|
+
|
|
287
|
+
console.log('Processing items as they arrive:')
|
|
288
|
+
let sum = 0
|
|
289
|
+
for await (const item of parser) {
|
|
290
|
+
const value = await item.readAsync()
|
|
291
|
+
sum += value as number
|
|
292
|
+
console.log(` Received: ${value}, Running sum: ${sum}`)
|
|
293
|
+
}
|
|
294
|
+
console.log(`Final sum: ${sum}`)
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
await parseAsyncArray()
|
|
298
|
+
|
|
299
|
+
// Example 3: Async key-value extraction
|
|
300
|
+
console.log('\n=== Example 3: Async Key-Value Extraction ===')
|
|
301
|
+
async function asyncKeyValueExtraction() {
|
|
302
|
+
const json = JSON.stringify({
|
|
303
|
+
user: {
|
|
304
|
+
profile: {
|
|
305
|
+
name: 'Bob',
|
|
306
|
+
email: 'bob@example.com',
|
|
307
|
+
},
|
|
308
|
+
scores: [85, 90, 95],
|
|
309
|
+
},
|
|
310
|
+
})
|
|
311
|
+
|
|
312
|
+
const stream = createAsyncByteStream(json, 15)
|
|
313
|
+
|
|
314
|
+
console.log('Extracting key-value pairs asynchronously:')
|
|
315
|
+
for await (const [key, value] of jsonKeyValueParserAsync(stream)) {
|
|
316
|
+
console.log(` ${key} = ${value}`)
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
await asyncKeyValueExtraction()
|
|
321
|
+
|
|
322
|
+
// Example 4: Simulated HTTP response
|
|
323
|
+
console.log('\n=== Example 4: Simulated HTTP Response ===')
|
|
324
|
+
async function processHttpResponse() {
|
|
325
|
+
// Simulate fetching JSON from an API
|
|
326
|
+
const responseData = JSON.stringify({
|
|
327
|
+
status: 'success',
|
|
328
|
+
data: {
|
|
329
|
+
users: [
|
|
330
|
+
{ id: 1, name: 'Alice' },
|
|
331
|
+
{ id: 2, name: 'Bob' },
|
|
332
|
+
{ id: 3, name: 'Charlie' },
|
|
333
|
+
],
|
|
334
|
+
},
|
|
335
|
+
})
|
|
336
|
+
|
|
337
|
+
const stream = createAsyncByteStream(responseData, 20)
|
|
338
|
+
const parser = new JsonObject(stream)
|
|
339
|
+
|
|
340
|
+
console.log('Processing HTTP response:')
|
|
341
|
+
for await (const [keyEntity, valueEntity] of parser) {
|
|
342
|
+
const key = keyEntity.read()
|
|
343
|
+
|
|
344
|
+
if (key === 'data') {
|
|
345
|
+
console.log(` Found ${key} field:`)
|
|
346
|
+
const dataValue = await valueEntity.readAsync()
|
|
347
|
+
const dataObj = dataValue as JsonObject
|
|
348
|
+
|
|
349
|
+
for await (const [dataKey, dataValueEntity] of dataObj) {
|
|
350
|
+
const dataKeyStr = dataKey.read()
|
|
351
|
+
if (dataKeyStr === 'users') {
|
|
352
|
+
console.log(` Found users array:`)
|
|
353
|
+
const usersValue = await dataValueEntity.readAsync()
|
|
354
|
+
const usersArray = usersValue as JsonArray
|
|
355
|
+
|
|
356
|
+
let count = 0
|
|
357
|
+
for await (const user of usersArray) {
|
|
358
|
+
const userData = await user.readAsync()
|
|
359
|
+
console.log(` User ${++count}:`, userData)
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
} else {
|
|
364
|
+
const value = await valueEntity.readValueAsync()
|
|
365
|
+
console.log(` ${key}: ${value}`)
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
await processHttpResponse()
|
|
371
|
+
|
|
372
|
+
// Example 5: Handle large dataset with async processing
|
|
373
|
+
console.log('\n=== Example 5: Process Large Dataset ===')
|
|
374
|
+
async function processLargeDataset() {
|
|
375
|
+
// Simulate a large dataset
|
|
376
|
+
const records = Array.from({ length: 100 }, (_, i) => ({
|
|
377
|
+
id: i + 1,
|
|
378
|
+
value: Math.random() * 100,
|
|
379
|
+
}))
|
|
380
|
+
|
|
381
|
+
const json = JSON.stringify({ records })
|
|
382
|
+
const stream = createAsyncByteStream(json, 50)
|
|
383
|
+
|
|
384
|
+
const parser = new JsonObject(stream)
|
|
385
|
+
|
|
386
|
+
console.log('Processing large dataset:')
|
|
387
|
+
let recordCount = 0
|
|
388
|
+
let totalValue = 0
|
|
389
|
+
|
|
390
|
+
for await (const [keyEntity, valueEntity] of parser) {
|
|
391
|
+
const key = keyEntity.read()
|
|
392
|
+
|
|
393
|
+
if (key === 'records') {
|
|
394
|
+
const value = await valueEntity.readAsync()
|
|
395
|
+
const array = value as JsonArray
|
|
396
|
+
|
|
397
|
+
for await (const item of array) {
|
|
398
|
+
const record = (await item.readAsync()) as any
|
|
399
|
+
recordCount++
|
|
400
|
+
totalValue += record.value
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
console.log(` Processed ${recordCount} records`)
|
|
406
|
+
console.log(` Average value: ${(totalValue / recordCount).toFixed(2)}`)
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
await processLargeDataset()
|
|
410
|
+
|
|
411
|
+
console.log('\n=== All async examples completed ===')
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
## Example 1: Basic stringify
|
|
415
|
+
|
|
416
|
+
```typescript
|
|
417
|
+
console.log('=== Example 1: Basic Stringify ===')
|
|
418
|
+
const simpleObj = {
|
|
419
|
+
name: 'Alice',
|
|
420
|
+
age: 30,
|
|
421
|
+
active: true,
|
|
422
|
+
balance: null,
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
console.log('Original object:', simpleObj)
|
|
426
|
+
console.log('Stringified (compact):')
|
|
427
|
+
const compact = Array.from(jsonStreamStringify(simpleObj)).join('')
|
|
428
|
+
console.log(compact)
|
|
429
|
+
|
|
430
|
+
console.log('\nStringified (pretty-printed):')
|
|
431
|
+
const pretty = Array.from(jsonStreamStringify(simpleObj, null, 2)).join('')
|
|
432
|
+
console.log(pretty)
|
|
433
|
+
|
|
434
|
+
// Example 2: Stringify with chunking
|
|
435
|
+
console.log('\n=== Example 2: Stringify with Chunking ===')
|
|
436
|
+
const largeString = 'x'.repeat(100)
|
|
437
|
+
const objWithLargeString = { data: largeString }
|
|
438
|
+
|
|
439
|
+
console.log('Object with 100-char string, chunked at 30 bytes:')
|
|
440
|
+
let chunkCount = 0
|
|
441
|
+
for (const chunk of jsonStreamStringify(objWithLargeString, null, 0, {
|
|
442
|
+
stringChunkSize: 30,
|
|
443
|
+
})) {
|
|
444
|
+
console.log(
|
|
445
|
+
` Chunk ${++chunkCount}: "${chunk.substring(0, 40)}${chunk.length > 40 ? '...' : ''}" (${chunk.length} chars)`,
|
|
446
|
+
)
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// Example 3: Stringify nested structures
|
|
450
|
+
console.log('\n=== Example 3: Nested Structures ===')
|
|
451
|
+
const nested = {
|
|
452
|
+
user: {
|
|
453
|
+
name: 'Bob',
|
|
454
|
+
profile: {
|
|
455
|
+
email: 'bob@example.com',
|
|
456
|
+
age: 25,
|
|
457
|
+
},
|
|
458
|
+
},
|
|
459
|
+
scores: [95, 87, 92],
|
|
460
|
+
metadata: {
|
|
461
|
+
created: '2025-01-01',
|
|
462
|
+
updated: '2025-11-30',
|
|
463
|
+
},
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
console.log('Nested object stringified:')
|
|
467
|
+
const nestedJson = Array.from(jsonStreamStringify(nested, null, 2)).join('')
|
|
468
|
+
console.log(nestedJson)
|
|
469
|
+
|
|
470
|
+
// Example 4: Using a replacer function
|
|
471
|
+
console.log('\n=== Example 4: With Replacer Function ===')
|
|
472
|
+
const withSecrets = {
|
|
473
|
+
username: 'alice',
|
|
474
|
+
password: 'secret123',
|
|
475
|
+
apiKey: 'key-12345',
|
|
476
|
+
public: 'visible data',
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
const replacer = (key: string, value: any) => {
|
|
480
|
+
if (key === 'password' || key === 'apiKey') {
|
|
481
|
+
return '***REDACTED***'
|
|
482
|
+
}
|
|
483
|
+
return value
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
console.log('Original object:', withSecrets)
|
|
487
|
+
console.log('Stringified with replacer:')
|
|
488
|
+
const redacted = Array.from(jsonStreamStringify(withSecrets, replacer, 2)).join(
|
|
489
|
+
'',
|
|
490
|
+
)
|
|
491
|
+
console.log(redacted)
|
|
492
|
+
|
|
493
|
+
// Example 5: Stringify to bytes
|
|
494
|
+
console.log('\n=== Example 5: Stringify to Bytes ===')
|
|
495
|
+
const dataObj = { message: 'Hello', count: 42 }
|
|
496
|
+
|
|
497
|
+
console.log('Converting to byte arrays:')
|
|
498
|
+
let totalBytes = 0
|
|
499
|
+
for (const bytes of jsonStreamStringifyBytes(dataObj)) {
|
|
500
|
+
totalBytes += bytes.length
|
|
501
|
+
console.log(
|
|
502
|
+
` Chunk: ${bytes.length} bytes - [${Array.from(bytes.slice(0, 20)).join(', ')}${bytes.length > 20 ? '...' : ''}]`,
|
|
503
|
+
)
|
|
504
|
+
}
|
|
505
|
+
console.log(`Total bytes: ${totalBytes}`)
|
|
506
|
+
|
|
507
|
+
// Example 6: Stream large array
|
|
508
|
+
console.log('\n=== Example 6: Stream Large Array ===')
|
|
509
|
+
const largeArray = Array.from({ length: 50 }, (_, i) => ({
|
|
510
|
+
id: i + 1,
|
|
511
|
+
value: Math.random(),
|
|
512
|
+
}))
|
|
513
|
+
|
|
514
|
+
console.log(`Streaming array with ${largeArray.length} objects:`)
|
|
515
|
+
let streamedChunks = 0
|
|
516
|
+
for (const chunk of jsonStreamStringify(largeArray, null, 0)) {
|
|
517
|
+
streamedChunks++
|
|
518
|
+
// In a real scenario, you might write each chunk to a file or network stream
|
|
519
|
+
}
|
|
520
|
+
console.log(`Generated ${streamedChunks} chunks`)
|
|
521
|
+
console.log(
|
|
522
|
+
'First 200 chars:',
|
|
523
|
+
Array.from(jsonStreamStringify(largeArray)).join('').substring(0, 200) +
|
|
524
|
+
'...',
|
|
525
|
+
)
|
|
526
|
+
|
|
527
|
+
// Example 7: Special values
|
|
528
|
+
console.log('\n=== Example 7: Special Values ===')
|
|
529
|
+
const specialValues = {
|
|
530
|
+
normal: 42,
|
|
531
|
+
infinity: Infinity,
|
|
532
|
+
negInfinity: -Infinity,
|
|
533
|
+
notANumber: NaN,
|
|
534
|
+
undef: undefined,
|
|
535
|
+
nul: null,
|
|
536
|
+
emptyArray: [],
|
|
537
|
+
emptyObject: {},
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
console.log('Object with special values:')
|
|
541
|
+
const specialJson = Array.from(
|
|
542
|
+
jsonStreamStringify(specialValues, null, 2),
|
|
543
|
+
).join('')
|
|
544
|
+
console.log(specialJson)
|
|
545
|
+
console.log(
|
|
546
|
+
'\nNote: Infinity, -Infinity, and NaN become null (JSON standard behavior)',
|
|
547
|
+
)
|
|
548
|
+
console.log(
|
|
549
|
+
'Note: undefined properties are omitted in objects, become null in arrays',
|
|
550
|
+
)
|
|
551
|
+
|
|
552
|
+
// Example 8: Comparison with JSON.stringify
|
|
553
|
+
console.log('\n=== Example 8: Verify Output Matches JSON.stringify ===')
|
|
554
|
+
const testObj = {
|
|
555
|
+
a: 1,
|
|
556
|
+
b: 'text',
|
|
557
|
+
c: [1, 2, 3],
|
|
558
|
+
d: { nested: true },
|
|
559
|
+
e: null,
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
const streamResult = Array.from(jsonStreamStringify(testObj, null, 2)).join('')
|
|
563
|
+
const standardResult = JSON.stringify(testObj, null, 2)
|
|
564
|
+
|
|
565
|
+
console.log('Output matches JSON.stringify:', streamResult === standardResult)
|
|
566
|
+
console.log('Stream result:', streamResult)
|
|
567
|
+
```
|
|
568
|
+
|
|
569
|
+
## Example 1: Feed bytes one at a time
|
|
570
|
+
|
|
571
|
+
```typescript
|
|
572
|
+
console.log('=== Example 1: Feed Bytes One at a Time ===')
|
|
573
|
+
const json1 = '{"name": "Alice"}'
|
|
574
|
+
const parser1 = new JsonObject()
|
|
575
|
+
|
|
576
|
+
console.log('Feeding bytes individually:')
|
|
577
|
+
const bytes1 = stringToBytes(json1)
|
|
578
|
+
for (let i = 0; i < bytes1.length; i++) {
|
|
579
|
+
parser1.feed(bytes1[i])
|
|
580
|
+
console.log(
|
|
581
|
+
` Fed ${i + 1}/${bytes1.length} bytes: "${String.fromCharCode(bytes1[i])}"`,
|
|
582
|
+
)
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
const result1 = parser1.read()
|
|
586
|
+
console.log('Result:', result1)
|
|
587
|
+
|
|
588
|
+
// Example 2: Feed in chunks
|
|
589
|
+
console.log('\n=== Example 2: Feed in Chunks ===')
|
|
590
|
+
const json2 = '{"id": 123, "active": true, "score": 95.5}'
|
|
591
|
+
const parser2 = new JsonObject()
|
|
592
|
+
|
|
593
|
+
const bytes2 = stringToBytes(json2)
|
|
594
|
+
const chunkSize = 10
|
|
595
|
+
|
|
596
|
+
console.log(`Feeding in chunks of ${chunkSize}:`)
|
|
597
|
+
for (let i = 0; i < bytes2.length; i += chunkSize) {
|
|
598
|
+
const chunk = bytes2.slice(i, i + chunkSize)
|
|
599
|
+
parser2.feed(...chunk)
|
|
600
|
+
|
|
601
|
+
const chunkStr = new TextDecoder().decode(new Uint8Array(chunk))
|
|
602
|
+
console.log(` Chunk ${Math.floor(i / chunkSize) + 1}: "${chunkStr}"`)
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
const result2 = parser2.read()
|
|
606
|
+
console.log('Result:', result2)
|
|
607
|
+
|
|
608
|
+
// Example 3: Feed as you parse (streaming members)
|
|
609
|
+
console.log('\n=== Example 3: Feed Then Parse Members ===')
|
|
610
|
+
const json3 = '{"a": 1, "b": 2, "c": 3}'
|
|
611
|
+
const parser3 = new JsonObject()
|
|
612
|
+
|
|
613
|
+
// Feed all at once
|
|
614
|
+
parser3.feed(...stringToBytes(json3))
|
|
615
|
+
|
|
616
|
+
console.log('Parsing members after feeding:')
|
|
617
|
+
for (const [keyEntity, valueEntity] of parser3.members()) {
|
|
618
|
+
const key = keyEntity.read()
|
|
619
|
+
const value = valueEntity.read().read()
|
|
620
|
+
console.log(` ${key}: ${value}`)
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
// Example 4: Try parse pattern - checking if we have enough data
|
|
624
|
+
console.log('\n=== Example 4: Try Parse Pattern ===')
|
|
625
|
+
const json4 = '{"complete": true}'
|
|
626
|
+
const parser4 = new JsonObject()
|
|
627
|
+
const bytes4 = stringToBytes(json4)
|
|
628
|
+
|
|
629
|
+
console.log('Feeding incrementally and checking if parseable:')
|
|
630
|
+
for (let i = 0; i < bytes4.length; i++) {
|
|
631
|
+
parser4.feed(bytes4[i])
|
|
632
|
+
|
|
633
|
+
const result = parser4.tryParse((p) => {
|
|
634
|
+
return p.read()
|
|
635
|
+
})
|
|
636
|
+
|
|
637
|
+
if (result !== undefined) {
|
|
638
|
+
console.log(` ✓ Successfully parsed after ${i + 1} bytes:`, result)
|
|
639
|
+
break
|
|
640
|
+
} else {
|
|
641
|
+
console.log(` ✗ Not enough data after ${i + 1} bytes`)
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// Example 5: Feeding array incrementally
|
|
646
|
+
console.log('\n=== Example 5: Array Incremental Feeding ===')
|
|
647
|
+
const json5 = '[10, 20, 30, 40, 50]'
|
|
648
|
+
const parser5 = new JsonArray()
|
|
649
|
+
|
|
650
|
+
console.log('Feeding array in small chunks:')
|
|
651
|
+
const bytes5 = stringToBytes(json5)
|
|
652
|
+
const feedSize = 5
|
|
653
|
+
|
|
654
|
+
for (let i = 0; i < bytes5.length; i += feedSize) {
|
|
655
|
+
const chunk = bytes5.slice(i, i + feedSize)
|
|
656
|
+
parser5.feed(...chunk)
|
|
657
|
+
console.log(
|
|
658
|
+
` Fed chunk: "${new TextDecoder().decode(new Uint8Array(chunk))}"`,
|
|
659
|
+
)
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
console.log('Parsing items:')
|
|
663
|
+
for (const item of parser5.items()) {
|
|
664
|
+
console.log(` Item: ${item.read()}`)
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
// Example 6: Simulating network chunks
|
|
668
|
+
console.log('\n=== Example 6: Simulating Network Chunks ===')
|
|
669
|
+
const networkData = JSON.stringify({
|
|
670
|
+
status: 'ok',
|
|
671
|
+
data: {
|
|
672
|
+
users: [
|
|
673
|
+
{ id: 1, name: 'Alice' },
|
|
674
|
+
{ id: 2, name: 'Bob' },
|
|
675
|
+
],
|
|
676
|
+
},
|
|
677
|
+
})
|
|
678
|
+
|
|
679
|
+
const parser6 = new JsonObject()
|
|
680
|
+
|
|
681
|
+
// Simulate receiving data in irregular chunks (like network packets)
|
|
682
|
+
const chunkSizes = [15, 8, 25, 12, 30, 1000] // Last chunk larger than remaining data
|
|
683
|
+
const bytes6 = stringToBytes(networkData)
|
|
684
|
+
let position = 0
|
|
685
|
+
|
|
686
|
+
console.log('Simulating network packet arrival:')
|
|
687
|
+
for (const size of chunkSizes) {
|
|
688
|
+
if (position >= bytes6.length) break
|
|
689
|
+
|
|
690
|
+
const chunk = bytes6.slice(position, position + size)
|
|
691
|
+
parser6.feed(...chunk)
|
|
692
|
+
|
|
693
|
+
const chunkText = new TextDecoder().decode(new Uint8Array(chunk))
|
|
694
|
+
console.log(
|
|
695
|
+
` Packet ${chunkSizes.indexOf(size) + 1}: ${chunk.length} bytes - "${chunkText.substring(0, 30)}${chunkText.length > 30 ? '...' : ''}"`,
|
|
696
|
+
)
|
|
697
|
+
|
|
698
|
+
position += size
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
const result6 = parser6.read()
|
|
702
|
+
console.log('Parsed result:', JSON.stringify(result6, null, 2))
|
|
703
|
+
|
|
704
|
+
// Example 7: Feeding with mixed types
|
|
705
|
+
console.log('\n=== Example 7: Feed with Arrays and Individual Bytes ===')
|
|
706
|
+
const json7 = '{"mixed": "feeding"}'
|
|
707
|
+
const parser7 = new JsonObject()
|
|
708
|
+
|
|
709
|
+
// Can feed individual bytes or arrays
|
|
710
|
+
parser7.feed(123) // {
|
|
711
|
+
parser7.feed([34, 109, 105, 120, 101, 100, 34]) // "mixed"
|
|
712
|
+
parser7.feed(58) // :
|
|
713
|
+
parser7.feed([32, 34]) // space and "
|
|
714
|
+
parser7.feed(...[102, 101, 101, 100, 105, 110, 103]) // feeding
|
|
715
|
+
parser7.feed(34, 125) // " and }
|
|
716
|
+
|
|
717
|
+
const result7 = parser7.read()
|
|
718
|
+
console.log('Result:', result7)
|
|
719
|
+
console.log('Note: Can feed bytes individually, as arrays, or spread arrays')
|
|
720
|
+
```
|
|
721
|
+
|
|
722
|
+
## Scenario 1: Processing a configuration file
|
|
723
|
+
|
|
724
|
+
```typescript
|
|
725
|
+
console.log('=== Scenario 1: Configuration File Processing ===')
|
|
726
|
+
function processConfig() {
|
|
727
|
+
const configJson = JSON.stringify({
|
|
728
|
+
database: {
|
|
729
|
+
host: 'localhost',
|
|
730
|
+
port: 5432,
|
|
731
|
+
pool: { min: 2, max: 10 },
|
|
732
|
+
},
|
|
733
|
+
api: {
|
|
734
|
+
port: 8080,
|
|
735
|
+
timeout: 30000,
|
|
736
|
+
},
|
|
737
|
+
features: {
|
|
738
|
+
analytics: true,
|
|
739
|
+
debugging: false,
|
|
740
|
+
},
|
|
741
|
+
})
|
|
742
|
+
|
|
743
|
+
console.log('Extracting all configuration values:')
|
|
744
|
+
const config: Record<string, any> = {}
|
|
745
|
+
|
|
746
|
+
for (const [key, value] of jsonKeyValueParser(configJson)) {
|
|
747
|
+
config[key] = value
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// Access nested values easily
|
|
751
|
+
console.log(' Database host:', config['database.host'])
|
|
752
|
+
console.log(' Database pool max:', config['database.pool.max'])
|
|
753
|
+
console.log(' API port:', config['api.port'])
|
|
754
|
+
console.log(' Analytics enabled:', config['features.analytics'])
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
processConfig()
|
|
758
|
+
|
|
759
|
+
// Scenario 2: Log file analysis
|
|
760
|
+
console.log('\n=== Scenario 2: Log File Analysis ===')
|
|
761
|
+
function analyzeLogEntries() {
|
|
762
|
+
const logEntries = JSON.stringify({
|
|
763
|
+
logs: [
|
|
764
|
+
{
|
|
765
|
+
timestamp: '2025-11-30T10:00:00Z',
|
|
766
|
+
level: 'ERROR',
|
|
767
|
+
message: 'Connection failed',
|
|
768
|
+
},
|
|
769
|
+
{
|
|
770
|
+
timestamp: '2025-11-30T10:01:00Z',
|
|
771
|
+
level: 'INFO',
|
|
772
|
+
message: 'Retry successful',
|
|
773
|
+
},
|
|
774
|
+
{
|
|
775
|
+
timestamp: '2025-11-30T10:02:00Z',
|
|
776
|
+
level: 'ERROR',
|
|
777
|
+
message: 'Timeout',
|
|
778
|
+
},
|
|
779
|
+
{
|
|
780
|
+
timestamp: '2025-11-30T10:03:00Z',
|
|
781
|
+
level: 'WARN',
|
|
782
|
+
message: 'High memory usage',
|
|
783
|
+
},
|
|
784
|
+
],
|
|
785
|
+
})
|
|
786
|
+
|
|
787
|
+
const parser = new JsonObject()
|
|
788
|
+
parser.feed(...stringToBytes(logEntries))
|
|
789
|
+
|
|
790
|
+
const stats = { ERROR: 0, INFO: 0, WARN: 0 }
|
|
791
|
+
|
|
792
|
+
console.log('Analyzing log entries:')
|
|
793
|
+
for (const [keyEntity, valueEntity] of parser.members()) {
|
|
794
|
+
const key = keyEntity.read()
|
|
795
|
+
|
|
796
|
+
if (key === 'logs') {
|
|
797
|
+
const logsValue = valueEntity.read()
|
|
798
|
+
if (logsValue instanceof JsonArray) {
|
|
799
|
+
for (const logEntry of logsValue.items()) {
|
|
800
|
+
const entry = logEntry.read() as any
|
|
801
|
+
stats[entry.level as keyof typeof stats]++
|
|
802
|
+
|
|
803
|
+
if (entry.level === 'ERROR') {
|
|
804
|
+
console.log(
|
|
805
|
+
` ERROR at ${entry.timestamp}: ${entry.message}`,
|
|
806
|
+
)
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
console.log('\nLog Statistics:')
|
|
814
|
+
console.log(` Errors: ${stats.ERROR}`)
|
|
815
|
+
console.log(` Warnings: ${stats.WARN}`)
|
|
816
|
+
console.log(` Info: ${stats.INFO}`)
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
analyzeLogEntries()
|
|
820
|
+
|
|
821
|
+
// Scenario 3: API response transformation
|
|
822
|
+
console.log('\n=== Scenario 3: API Response Transformation ===')
|
|
823
|
+
function transformApiResponse() {
|
|
824
|
+
const apiResponse = JSON.stringify({
|
|
825
|
+
status: 'success',
|
|
826
|
+
data: {
|
|
827
|
+
users: [
|
|
828
|
+
{ id: 1, firstName: 'Alice', lastName: 'Smith', age: 30 },
|
|
829
|
+
{ id: 2, firstName: 'Bob', lastName: 'Jones', age: 25 },
|
|
830
|
+
],
|
|
831
|
+
},
|
|
832
|
+
})
|
|
833
|
+
|
|
834
|
+
const parser = new JsonObject()
|
|
835
|
+
parser.feed(...stringToBytes(apiResponse))
|
|
836
|
+
|
|
837
|
+
const transformedUsers: any[] = []
|
|
838
|
+
|
|
839
|
+
console.log('Transforming API response:')
|
|
840
|
+
for (const [keyEntity, valueEntity] of parser.members()) {
|
|
841
|
+
const key = keyEntity.read()
|
|
842
|
+
|
|
843
|
+
if (key === 'data') {
|
|
844
|
+
const dataValue = valueEntity.read() as JsonObject
|
|
845
|
+
for (const [
|
|
846
|
+
dataKeyEntity,
|
|
847
|
+
dataValueEntity,
|
|
848
|
+
] of dataValue.members()) {
|
|
849
|
+
const dataKey = dataKeyEntity.read()
|
|
850
|
+
|
|
851
|
+
if (dataKey === 'users') {
|
|
852
|
+
const usersValue = dataValueEntity.read() as JsonArray
|
|
853
|
+
for (const userEntity of usersValue.items()) {
|
|
854
|
+
const user = userEntity.read() as any
|
|
855
|
+
// Transform: combine firstName and lastName
|
|
856
|
+
transformedUsers.push({
|
|
857
|
+
id: user.id,
|
|
858
|
+
fullName: `${user.firstName} ${user.lastName}`,
|
|
859
|
+
age: user.age,
|
|
860
|
+
})
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
console.log('Transformed users:', transformedUsers)
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
transformApiResponse()
|
|
871
|
+
|
|
872
|
+
// Scenario 4: Data validation
|
|
873
|
+
console.log('\n=== Scenario 4: Data Validation ===')
|
|
874
|
+
function validateData() {
|
|
875
|
+
const userData = JSON.stringify({
|
|
876
|
+
users: [
|
|
877
|
+
{ id: 1, email: 'alice@example.com', age: 30 },
|
|
878
|
+
{ id: 2, email: 'invalid-email', age: 25 },
|
|
879
|
+
{ id: 3, email: 'bob@example.com', age: -5 }, // Invalid age
|
|
880
|
+
{ id: 4, email: 'charlie@example.com', age: 35 },
|
|
881
|
+
],
|
|
882
|
+
})
|
|
883
|
+
|
|
884
|
+
const parser = new JsonObject()
|
|
885
|
+
parser.feed(...stringToBytes(userData))
|
|
886
|
+
|
|
887
|
+
const errors: string[] = []
|
|
888
|
+
|
|
889
|
+
console.log('Validating user data:')
|
|
890
|
+
for (const [keyEntity, valueEntity] of parser.members()) {
|
|
891
|
+
const key = keyEntity.read()
|
|
892
|
+
|
|
893
|
+
if (key === 'users') {
|
|
894
|
+
const usersValue = valueEntity.read() as JsonArray
|
|
895
|
+
let index = 0
|
|
896
|
+
|
|
897
|
+
for (const userEntity of usersValue.items()) {
|
|
898
|
+
const user = userEntity.read() as any
|
|
899
|
+
|
|
900
|
+
// Validate email
|
|
901
|
+
if (!user.email.includes('@')) {
|
|
902
|
+
errors.push(`User ${user.id}: Invalid email format`)
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
// Validate age
|
|
906
|
+
if (user.age < 0 || user.age > 120) {
|
|
907
|
+
errors.push(`User ${user.id}: Invalid age (${user.age})`)
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
index++
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
if (errors.length > 0) {
|
|
916
|
+
console.log('Validation errors found:')
|
|
917
|
+
errors.forEach((err) => console.log(` ✗ ${err}`))
|
|
918
|
+
} else {
|
|
919
|
+
console.log('✓ All data valid')
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
validateData()
|
|
924
|
+
|
|
925
|
+
// Scenario 5: Generating a CSV export
|
|
926
|
+
console.log('\n=== Scenario 5: Generate CSV from JSON ===')
|
|
927
|
+
function jsonToCsv() {
|
|
928
|
+
const data = [
|
|
929
|
+
{ id: 1, name: 'Alice', department: 'Engineering', salary: 95000 },
|
|
930
|
+
{ id: 2, name: 'Bob', department: 'Sales', salary: 85000 },
|
|
931
|
+
{ id: 3, name: 'Charlie', department: 'Engineering', salary: 90000 },
|
|
932
|
+
]
|
|
933
|
+
|
|
934
|
+
console.log('Converting JSON array to CSV:')
|
|
935
|
+
|
|
936
|
+
// Headers
|
|
937
|
+
const headers = Object.keys(data[0])
|
|
938
|
+
console.log(headers.join(','))
|
|
939
|
+
|
|
940
|
+
// Process each record
|
|
941
|
+
const parser = new JsonArray()
|
|
942
|
+
parser.feed(...stringToBytes(JSON.stringify(data)))
|
|
943
|
+
|
|
944
|
+
for (const item of parser.items()) {
|
|
945
|
+
const record = item.read() as any
|
|
946
|
+
const row = headers.map((h) => record[h]).join(',')
|
|
947
|
+
console.log(row)
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
jsonToCsv()
|
|
952
|
+
|
|
953
|
+
// Scenario 6: Filtering large datasets
|
|
954
|
+
console.log('\n=== Scenario 6: Filter Large Dataset ===')
|
|
955
|
+
function filterLargeDataset() {
|
|
956
|
+
// Simulate a large dataset of transactions
|
|
957
|
+
const transactions = Array.from({ length: 20 }, (_, i) => ({
|
|
958
|
+
id: i + 1,
|
|
959
|
+
amount: Math.floor(Math.random() * 1000),
|
|
960
|
+
type: i % 3 === 0 ? 'refund' : 'payment',
|
|
961
|
+
date: '2025-11-30',
|
|
962
|
+
}))
|
|
963
|
+
|
|
964
|
+
const parser = new JsonArray()
|
|
965
|
+
parser.feed(...stringToBytes(JSON.stringify(transactions)))
|
|
966
|
+
|
|
967
|
+
console.log('Filtering for high-value payments (>500):')
|
|
968
|
+
let totalFiltered = 0
|
|
969
|
+
let sumFiltered = 0
|
|
970
|
+
|
|
971
|
+
for (const item of parser.items()) {
|
|
972
|
+
const tx = item.read() as any
|
|
973
|
+
|
|
974
|
+
if (tx.type === 'payment' && tx.amount > 500) {
|
|
975
|
+
console.log(` Transaction ${tx.id}: $${tx.amount}`)
|
|
976
|
+
totalFiltered++
|
|
977
|
+
sumFiltered += tx.amount
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
console.log(
|
|
982
|
+
`\nFound ${totalFiltered} transactions totaling $${sumFiltered}`,
|
|
983
|
+
)
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
filterLargeDataset()
|
|
987
|
+
|
|
988
|
+
// Scenario 7: Building a report
|
|
989
|
+
console.log('\n=== Scenario 7: Generate Report ===')
|
|
990
|
+
function generateReport() {
|
|
991
|
+
const salesData = {
|
|
992
|
+
period: 'Q4 2025',
|
|
993
|
+
regions: [
|
|
994
|
+
{ name: 'North', sales: 125000, target: 100000 },
|
|
995
|
+
{ name: 'South', sales: 95000, target: 100000 },
|
|
996
|
+
{ name: 'East', sales: 110000, target: 100000 },
|
|
997
|
+
{ name: 'West', sales: 88000, target: 100000 },
|
|
998
|
+
],
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
const parser = new JsonObject()
|
|
1002
|
+
parser.feed(...stringToBytes(JSON.stringify(salesData)))
|
|
1003
|
+
|
|
1004
|
+
console.log('Sales Report:')
|
|
1005
|
+
|
|
1006
|
+
for (const [keyEntity, valueEntity] of parser.members()) {
|
|
1007
|
+
const key = keyEntity.read()
|
|
1008
|
+
|
|
1009
|
+
if (key === 'period') {
|
|
1010
|
+
console.log(`Period: ${valueEntity.read().read()}`)
|
|
1011
|
+
console.log('─'.repeat(50))
|
|
1012
|
+
} else if (key === 'regions') {
|
|
1013
|
+
const regionsValue = valueEntity.read() as JsonArray
|
|
1014
|
+
let totalSales = 0
|
|
1015
|
+
let totalTarget = 0
|
|
1016
|
+
|
|
1017
|
+
for (const regionEntity of regionsValue.items()) {
|
|
1018
|
+
const region = regionEntity.read() as any
|
|
1019
|
+
totalSales += region.sales
|
|
1020
|
+
totalTarget += region.target
|
|
1021
|
+
|
|
1022
|
+
const performance = (
|
|
1023
|
+
(region.sales / region.target) *
|
|
1024
|
+
100
|
|
1025
|
+
).toFixed(1)
|
|
1026
|
+
const status = region.sales >= region.target ? '✓' : '✗'
|
|
1027
|
+
|
|
1028
|
+
console.log(
|
|
1029
|
+
`${status} ${region.name.padEnd(10)} Sales: $${region.sales.toLocaleString().padStart(10)} (${performance}% of target)`,
|
|
1030
|
+
)
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
console.log('─'.repeat(50))
|
|
1034
|
+
console.log(`Total Sales: $${totalSales.toLocaleString()}`)
|
|
1035
|
+
console.log(`Total Target: $${totalTarget.toLocaleString()}`)
|
|
1036
|
+
console.log(
|
|
1037
|
+
`Overall Performance: ${((totalSales / totalTarget) * 100).toFixed(1)}%`,
|
|
1038
|
+
)
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
generateReport()
|
|
1044
|
+
|
|
1045
|
+
console.log('\n=== All scenarios completed ===')
|
|
1046
|
+
```
|