json-stream-lite 1.0.0 → 1.0.2

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 ADDED
@@ -0,0 +1,1053 @@
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
+ // Note: The replacer function is called on each value (with the key parameter, which is '' for the root) during stringification.
472
+ console.log('\n=== Example 4: With Replacer Function ===')
473
+ const numbers = { a: 1, b: 2, c: 3 }
474
+
475
+ const replacer = (key: string, value: any) => {
476
+ // Transform objects by doubling all number values
477
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
478
+ const transformed: Record<string, any> = {}
479
+ for (const [k, v] of Object.entries(value)) {
480
+ transformed[k] = typeof v === 'number' ? v * 2 : v
481
+ }
482
+ return transformed
483
+ }
484
+ return value
485
+ }
486
+
487
+ console.log('Original object:', numbers)
488
+ console.log('Stringified with replacer (numbers doubled):')
489
+ const transformed = Array.from(jsonStreamStringify(numbers, replacer, 2)).join(
490
+ '',
491
+ )
492
+ console.log(transformed)
493
+ // Output:
494
+ // {
495
+ // "a": 2,
496
+ // "b": 4,
497
+ // "c": 6
498
+ // }
499
+
500
+ // Example 5: Stringify to bytes
501
+ console.log('\n=== Example 5: Stringify to Bytes ===')
502
+ const dataObj = { message: 'Hello', count: 42 }
503
+
504
+ console.log('Converting to byte arrays:')
505
+ let totalBytes = 0
506
+ for (const bytes of jsonStreamStringifyBytes(dataObj)) {
507
+ totalBytes += bytes.length
508
+ console.log(
509
+ ` Chunk: ${bytes.length} bytes - [${Array.from(bytes.slice(0, 20)).join(', ')}${bytes.length > 20 ? '...' : ''}]`,
510
+ )
511
+ }
512
+ console.log(`Total bytes: ${totalBytes}`)
513
+
514
+ // Example 6: Stream large array
515
+ console.log('\n=== Example 6: Stream Large Array ===')
516
+ const largeArray = Array.from({ length: 50 }, (_, i) => ({
517
+ id: i + 1,
518
+ value: Math.random(),
519
+ }))
520
+
521
+ console.log(`Streaming array with ${largeArray.length} objects:`)
522
+ let streamedChunks = 0
523
+ for (const chunk of jsonStreamStringify(largeArray, null, 0)) {
524
+ streamedChunks++
525
+ // In a real scenario, you might write each chunk to a file or network stream
526
+ }
527
+ console.log(`Generated ${streamedChunks} chunks`)
528
+ console.log(
529
+ 'First 200 chars:',
530
+ Array.from(jsonStreamStringify(largeArray)).join('').substring(0, 200) +
531
+ '...',
532
+ )
533
+
534
+ // Example 7: Special values
535
+ console.log('\n=== Example 7: Special Values ===')
536
+ const specialValues = {
537
+ normal: 42,
538
+ infinity: Infinity,
539
+ negInfinity: -Infinity,
540
+ notANumber: NaN,
541
+ undef: undefined,
542
+ nul: null,
543
+ emptyArray: [],
544
+ emptyObject: {},
545
+ }
546
+
547
+ console.log('Object with special values:')
548
+ const specialJson = Array.from(
549
+ jsonStreamStringify(specialValues, null, 2),
550
+ ).join('')
551
+ console.log(specialJson)
552
+ console.log(
553
+ '\nNote: Infinity, -Infinity, and NaN become null (JSON standard behavior)',
554
+ )
555
+ console.log(
556
+ 'Note: undefined properties are omitted in objects, become null in arrays',
557
+ )
558
+
559
+ // Example 8: Comparison with JSON.stringify
560
+ console.log('\n=== Example 8: Verify Output Matches JSON.stringify ===')
561
+ const testObj = {
562
+ a: 1,
563
+ b: 'text',
564
+ c: [1, 2, 3],
565
+ d: { nested: true },
566
+ e: null,
567
+ }
568
+
569
+ const streamResult = Array.from(jsonStreamStringify(testObj, null, 2)).join('')
570
+ const standardResult = JSON.stringify(testObj, null, 2)
571
+
572
+ console.log('Output matches JSON.stringify:', streamResult === standardResult)
573
+ console.log('Stream result:', streamResult)
574
+ ```
575
+
576
+ ## Example 1: Feed bytes one at a time
577
+
578
+ ```typescript
579
+ console.log('=== Example 1: Feed Bytes One at a Time ===')
580
+ const json1 = '{"name": "Alice"}'
581
+ const parser1 = new JsonObject()
582
+
583
+ console.log('Feeding bytes individually:')
584
+ const bytes1 = stringToBytes(json1)
585
+ for (let i = 0; i < bytes1.length; i++) {
586
+ parser1.feed(bytes1[i])
587
+ console.log(
588
+ ` Fed ${i + 1}/${bytes1.length} bytes: "${String.fromCharCode(bytes1[i])}"`,
589
+ )
590
+ }
591
+
592
+ const result1 = parser1.read()
593
+ console.log('Result:', result1)
594
+
595
+ // Example 2: Feed in chunks
596
+ console.log('\n=== Example 2: Feed in Chunks ===')
597
+ const json2 = '{"id": 123, "active": true, "score": 95.5}'
598
+ const parser2 = new JsonObject()
599
+
600
+ const bytes2 = stringToBytes(json2)
601
+ const chunkSize = 10
602
+
603
+ console.log(`Feeding in chunks of ${chunkSize}:`)
604
+ for (let i = 0; i < bytes2.length; i += chunkSize) {
605
+ const chunk = bytes2.slice(i, i + chunkSize)
606
+ parser2.feed(...chunk)
607
+
608
+ const chunkStr = new TextDecoder().decode(new Uint8Array(chunk))
609
+ console.log(` Chunk ${Math.floor(i / chunkSize) + 1}: "${chunkStr}"`)
610
+ }
611
+
612
+ const result2 = parser2.read()
613
+ console.log('Result:', result2)
614
+
615
+ // Example 3: Feed as you parse (streaming members)
616
+ console.log('\n=== Example 3: Feed Then Parse Members ===')
617
+ const json3 = '{"a": 1, "b": 2, "c": 3}'
618
+ const parser3 = new JsonObject()
619
+
620
+ // Feed all at once
621
+ parser3.feed(...stringToBytes(json3))
622
+
623
+ console.log('Parsing members after feeding:')
624
+ for (const [keyEntity, valueEntity] of parser3.members()) {
625
+ const key = keyEntity.read()
626
+ const value = valueEntity.read().read()
627
+ console.log(` ${key}: ${value}`)
628
+ }
629
+
630
+ // Example 4: Try parse pattern - checking if we have enough data
631
+ console.log('\n=== Example 4: Try Parse Pattern ===')
632
+ const json4 = '{"complete": true}'
633
+ const parser4 = new JsonObject()
634
+ const bytes4 = stringToBytes(json4)
635
+
636
+ console.log('Feeding incrementally and checking if parseable:')
637
+ for (let i = 0; i < bytes4.length; i++) {
638
+ parser4.feed(bytes4[i])
639
+
640
+ const result = parser4.tryParse((p) => {
641
+ return p.read()
642
+ })
643
+
644
+ if (result !== undefined) {
645
+ console.log(` ✓ Successfully parsed after ${i + 1} bytes:`, result)
646
+ break
647
+ } else {
648
+ console.log(` ✗ Not enough data after ${i + 1} bytes`)
649
+ }
650
+ }
651
+
652
+ // Example 5: Feeding array incrementally
653
+ console.log('\n=== Example 5: Array Incremental Feeding ===')
654
+ const json5 = '[10, 20, 30, 40, 50]'
655
+ const parser5 = new JsonArray()
656
+
657
+ console.log('Feeding array in small chunks:')
658
+ const bytes5 = stringToBytes(json5)
659
+ const feedSize = 5
660
+
661
+ for (let i = 0; i < bytes5.length; i += feedSize) {
662
+ const chunk = bytes5.slice(i, i + feedSize)
663
+ parser5.feed(...chunk)
664
+ console.log(
665
+ ` Fed chunk: "${new TextDecoder().decode(new Uint8Array(chunk))}"`,
666
+ )
667
+ }
668
+
669
+ console.log('Parsing items:')
670
+ for (const item of parser5.items()) {
671
+ console.log(` Item: ${item.read()}`)
672
+ }
673
+
674
+ // Example 6: Simulating network chunks
675
+ console.log('\n=== Example 6: Simulating Network Chunks ===')
676
+ const networkData = JSON.stringify({
677
+ status: 'ok',
678
+ data: {
679
+ users: [
680
+ { id: 1, name: 'Alice' },
681
+ { id: 2, name: 'Bob' },
682
+ ],
683
+ },
684
+ })
685
+
686
+ const parser6 = new JsonObject()
687
+
688
+ // Simulate receiving data in irregular chunks (like network packets)
689
+ const chunkSizes = [15, 8, 25, 12, 30, 1000] // Last chunk larger than remaining data
690
+ const bytes6 = stringToBytes(networkData)
691
+ let position = 0
692
+
693
+ console.log('Simulating network packet arrival:')
694
+ for (const size of chunkSizes) {
695
+ if (position >= bytes6.length) break
696
+
697
+ const chunk = bytes6.slice(position, position + size)
698
+ parser6.feed(...chunk)
699
+
700
+ const chunkText = new TextDecoder().decode(new Uint8Array(chunk))
701
+ console.log(
702
+ ` Packet ${chunkSizes.indexOf(size) + 1}: ${chunk.length} bytes - "${chunkText.substring(0, 30)}${chunkText.length > 30 ? '...' : ''}"`,
703
+ )
704
+
705
+ position += size
706
+ }
707
+
708
+ const result6 = parser6.read()
709
+ console.log('Parsed result:', JSON.stringify(result6, null, 2))
710
+
711
+ // Example 7: Feeding with mixed types
712
+ console.log('\n=== Example 7: Feed with Arrays and Individual Bytes ===')
713
+ const json7 = '{"mixed": "feeding"}'
714
+ const parser7 = new JsonObject()
715
+
716
+ // Can feed individual bytes or arrays
717
+ parser7.feed(123) // {
718
+ parser7.feed([34, 109, 105, 120, 101, 100, 34]) // "mixed"
719
+ parser7.feed(58) // :
720
+ parser7.feed([32, 34]) // space and "
721
+ parser7.feed(...[102, 101, 101, 100, 105, 110, 103]) // feeding
722
+ parser7.feed(34, 125) // " and }
723
+
724
+ const result7 = parser7.read()
725
+ console.log('Result:', result7)
726
+ console.log('Note: Can feed bytes individually, as arrays, or spread arrays')
727
+ ```
728
+
729
+ ## Scenario 1: Processing a configuration file
730
+
731
+ ```typescript
732
+ console.log('=== Scenario 1: Configuration File Processing ===')
733
+ function processConfig() {
734
+ const configJson = JSON.stringify({
735
+ database: {
736
+ host: 'localhost',
737
+ port: 5432,
738
+ pool: { min: 2, max: 10 },
739
+ },
740
+ api: {
741
+ port: 8080,
742
+ timeout: 30000,
743
+ },
744
+ features: {
745
+ analytics: true,
746
+ debugging: false,
747
+ },
748
+ })
749
+
750
+ console.log('Extracting all configuration values:')
751
+ const config: Record<string, any> = {}
752
+
753
+ for (const [key, value] of jsonKeyValueParser(configJson)) {
754
+ config[key] = value
755
+ }
756
+
757
+ // Access nested values easily
758
+ console.log(' Database host:', config['database.host'])
759
+ console.log(' Database pool max:', config['database.pool.max'])
760
+ console.log(' API port:', config['api.port'])
761
+ console.log(' Analytics enabled:', config['features.analytics'])
762
+ }
763
+
764
+ processConfig()
765
+
766
+ // Scenario 2: Log file analysis
767
+ console.log('\n=== Scenario 2: Log File Analysis ===')
768
+ function analyzeLogEntries() {
769
+ const logEntries = JSON.stringify({
770
+ logs: [
771
+ {
772
+ timestamp: '2025-11-30T10:00:00Z',
773
+ level: 'ERROR',
774
+ message: 'Connection failed',
775
+ },
776
+ {
777
+ timestamp: '2025-11-30T10:01:00Z',
778
+ level: 'INFO',
779
+ message: 'Retry successful',
780
+ },
781
+ {
782
+ timestamp: '2025-11-30T10:02:00Z',
783
+ level: 'ERROR',
784
+ message: 'Timeout',
785
+ },
786
+ {
787
+ timestamp: '2025-11-30T10:03:00Z',
788
+ level: 'WARN',
789
+ message: 'High memory usage',
790
+ },
791
+ ],
792
+ })
793
+
794
+ const parser = new JsonObject()
795
+ parser.feed(...stringToBytes(logEntries))
796
+
797
+ const stats = { ERROR: 0, INFO: 0, WARN: 0 }
798
+
799
+ console.log('Analyzing log entries:')
800
+ for (const [keyEntity, valueEntity] of parser.members()) {
801
+ const key = keyEntity.read()
802
+
803
+ if (key === 'logs') {
804
+ const logsValue = valueEntity.read()
805
+ if (logsValue instanceof JsonArray) {
806
+ for (const logEntry of logsValue.items()) {
807
+ const entry = logEntry.read() as any
808
+ stats[entry.level as keyof typeof stats]++
809
+
810
+ if (entry.level === 'ERROR') {
811
+ console.log(
812
+ ` ERROR at ${entry.timestamp}: ${entry.message}`,
813
+ )
814
+ }
815
+ }
816
+ }
817
+ }
818
+ }
819
+
820
+ console.log('\nLog Statistics:')
821
+ console.log(` Errors: ${stats.ERROR}`)
822
+ console.log(` Warnings: ${stats.WARN}`)
823
+ console.log(` Info: ${stats.INFO}`)
824
+ }
825
+
826
+ analyzeLogEntries()
827
+
828
+ // Scenario 3: API response transformation
829
+ console.log('\n=== Scenario 3: API Response Transformation ===')
830
+ function transformApiResponse() {
831
+ const apiResponse = JSON.stringify({
832
+ status: 'success',
833
+ data: {
834
+ users: [
835
+ { id: 1, firstName: 'Alice', lastName: 'Smith', age: 30 },
836
+ { id: 2, firstName: 'Bob', lastName: 'Jones', age: 25 },
837
+ ],
838
+ },
839
+ })
840
+
841
+ const parser = new JsonObject()
842
+ parser.feed(...stringToBytes(apiResponse))
843
+
844
+ const transformedUsers: any[] = []
845
+
846
+ console.log('Transforming API response:')
847
+ for (const [keyEntity, valueEntity] of parser.members()) {
848
+ const key = keyEntity.read()
849
+
850
+ if (key === 'data') {
851
+ const dataValue = valueEntity.read() as JsonObject
852
+ for (const [
853
+ dataKeyEntity,
854
+ dataValueEntity,
855
+ ] of dataValue.members()) {
856
+ const dataKey = dataKeyEntity.read()
857
+
858
+ if (dataKey === 'users') {
859
+ const usersValue = dataValueEntity.read() as JsonArray
860
+ for (const userEntity of usersValue.items()) {
861
+ const user = userEntity.read() as any
862
+ // Transform: combine firstName and lastName
863
+ transformedUsers.push({
864
+ id: user.id,
865
+ fullName: `${user.firstName} ${user.lastName}`,
866
+ age: user.age,
867
+ })
868
+ }
869
+ }
870
+ }
871
+ }
872
+ }
873
+
874
+ console.log('Transformed users:', transformedUsers)
875
+ }
876
+
877
+ transformApiResponse()
878
+
879
+ // Scenario 4: Data validation
880
+ console.log('\n=== Scenario 4: Data Validation ===')
881
+ function validateData() {
882
+ const userData = JSON.stringify({
883
+ users: [
884
+ { id: 1, email: 'alice@example.com', age: 30 },
885
+ { id: 2, email: 'invalid-email', age: 25 },
886
+ { id: 3, email: 'bob@example.com', age: -5 }, // Invalid age
887
+ { id: 4, email: 'charlie@example.com', age: 35 },
888
+ ],
889
+ })
890
+
891
+ const parser = new JsonObject()
892
+ parser.feed(...stringToBytes(userData))
893
+
894
+ const errors: string[] = []
895
+
896
+ console.log('Validating user data:')
897
+ for (const [keyEntity, valueEntity] of parser.members()) {
898
+ const key = keyEntity.read()
899
+
900
+ if (key === 'users') {
901
+ const usersValue = valueEntity.read() as JsonArray
902
+ let index = 0
903
+
904
+ for (const userEntity of usersValue.items()) {
905
+ const user = userEntity.read() as any
906
+
907
+ // Validate email
908
+ if (!user.email.includes('@')) {
909
+ errors.push(`User ${user.id}: Invalid email format`)
910
+ }
911
+
912
+ // Validate age
913
+ if (user.age < 0 || user.age > 120) {
914
+ errors.push(`User ${user.id}: Invalid age (${user.age})`)
915
+ }
916
+
917
+ index++
918
+ }
919
+ }
920
+ }
921
+
922
+ if (errors.length > 0) {
923
+ console.log('Validation errors found:')
924
+ errors.forEach((err) => console.log(` ✗ ${err}`))
925
+ } else {
926
+ console.log('✓ All data valid')
927
+ }
928
+ }
929
+
930
+ validateData()
931
+
932
+ // Scenario 5: Generating a CSV export
933
+ console.log('\n=== Scenario 5: Generate CSV from JSON ===')
934
+ function jsonToCsv() {
935
+ const data = [
936
+ { id: 1, name: 'Alice', department: 'Engineering', salary: 95000 },
937
+ { id: 2, name: 'Bob', department: 'Sales', salary: 85000 },
938
+ { id: 3, name: 'Charlie', department: 'Engineering', salary: 90000 },
939
+ ]
940
+
941
+ console.log('Converting JSON array to CSV:')
942
+
943
+ // Headers
944
+ const headers = Object.keys(data[0])
945
+ console.log(headers.join(','))
946
+
947
+ // Process each record
948
+ const parser = new JsonArray()
949
+ parser.feed(...stringToBytes(JSON.stringify(data)))
950
+
951
+ for (const item of parser.items()) {
952
+ const record = item.read() as any
953
+ const row = headers.map((h) => record[h]).join(',')
954
+ console.log(row)
955
+ }
956
+ }
957
+
958
+ jsonToCsv()
959
+
960
+ // Scenario 6: Filtering large datasets
961
+ console.log('\n=== Scenario 6: Filter Large Dataset ===')
962
+ function filterLargeDataset() {
963
+ // Simulate a large dataset of transactions
964
+ const transactions = Array.from({ length: 20 }, (_, i) => ({
965
+ id: i + 1,
966
+ amount: Math.floor(Math.random() * 1000),
967
+ type: i % 3 === 0 ? 'refund' : 'payment',
968
+ date: '2025-11-30',
969
+ }))
970
+
971
+ const parser = new JsonArray()
972
+ parser.feed(...stringToBytes(JSON.stringify(transactions)))
973
+
974
+ console.log('Filtering for high-value payments (>500):')
975
+ let totalFiltered = 0
976
+ let sumFiltered = 0
977
+
978
+ for (const item of parser.items()) {
979
+ const tx = item.read() as any
980
+
981
+ if (tx.type === 'payment' && tx.amount > 500) {
982
+ console.log(` Transaction ${tx.id}: $${tx.amount}`)
983
+ totalFiltered++
984
+ sumFiltered += tx.amount
985
+ }
986
+ }
987
+
988
+ console.log(
989
+ `\nFound ${totalFiltered} transactions totaling $${sumFiltered}`,
990
+ )
991
+ }
992
+
993
+ filterLargeDataset()
994
+
995
+ // Scenario 7: Building a report
996
+ console.log('\n=== Scenario 7: Generate Report ===')
997
+ function generateReport() {
998
+ const salesData = {
999
+ period: 'Q4 2025',
1000
+ regions: [
1001
+ { name: 'North', sales: 125000, target: 100000 },
1002
+ { name: 'South', sales: 95000, target: 100000 },
1003
+ { name: 'East', sales: 110000, target: 100000 },
1004
+ { name: 'West', sales: 88000, target: 100000 },
1005
+ ],
1006
+ }
1007
+
1008
+ const parser = new JsonObject()
1009
+ parser.feed(...stringToBytes(JSON.stringify(salesData)))
1010
+
1011
+ console.log('Sales Report:')
1012
+
1013
+ for (const [keyEntity, valueEntity] of parser.members()) {
1014
+ const key = keyEntity.read()
1015
+
1016
+ if (key === 'period') {
1017
+ console.log(`Period: ${valueEntity.read().read()}`)
1018
+ console.log('─'.repeat(50))
1019
+ } else if (key === 'regions') {
1020
+ const regionsValue = valueEntity.read() as JsonArray
1021
+ let totalSales = 0
1022
+ let totalTarget = 0
1023
+
1024
+ for (const regionEntity of regionsValue.items()) {
1025
+ const region = regionEntity.read() as any
1026
+ totalSales += region.sales
1027
+ totalTarget += region.target
1028
+
1029
+ const performance = (
1030
+ (region.sales / region.target) *
1031
+ 100
1032
+ ).toFixed(1)
1033
+ const status = region.sales >= region.target ? '✓' : '✗'
1034
+
1035
+ console.log(
1036
+ `${status} ${region.name.padEnd(10)} Sales: $${region.sales.toLocaleString().padStart(10)} (${performance}% of target)`,
1037
+ )
1038
+ }
1039
+
1040
+ console.log('─'.repeat(50))
1041
+ console.log(`Total Sales: $${totalSales.toLocaleString()}`)
1042
+ console.log(`Total Target: $${totalTarget.toLocaleString()}`)
1043
+ console.log(
1044
+ `Overall Performance: ${((totalSales / totalTarget) * 100).toFixed(1)}%`,
1045
+ )
1046
+ }
1047
+ }
1048
+ }
1049
+
1050
+ generateReport()
1051
+
1052
+ console.log('\n=== All scenarios completed ===')
1053
+ ```