|
| 1 | +# Streaming |
| 2 | + |
| 3 | +`JsonWriter` can be used to incrementally write JSON data. |
| 4 | + |
| 5 | +Incremental processing is ideal for large documents or when you want to avoid building the entire JSON structure in memory. |
| 6 | + |
| 7 | +<!-- toc --> |
| 8 | + |
| 9 | +## Writing |
| 10 | + |
| 11 | +You can use `JsonWriter` to write JSON objects, arrays, and values step by step, directly to a file or any output stream. |
| 12 | + |
| 13 | +The process is similar to when you override `writeValue` to provide custom serialization. |
| 14 | + |
| 15 | +### Example: Writing a JSON Array of Objects |
| 16 | + |
| 17 | +Suppose you want to write a large array of objects to a file, one at a time: |
| 18 | + |
| 19 | +```nim |
| 20 | +{{#include ../examples/streamwrite0.nim}} |
| 21 | +``` |
| 22 | + |
| 23 | +Resulting file (`output.json`): |
| 24 | +```json |
| 25 | +[ |
| 26 | + { |
| 27 | + "id": 0, |
| 28 | + "name": "item0" |
| 29 | + }, |
| 30 | + { |
| 31 | + "id": 1, |
| 32 | + "name": "item1" |
| 33 | + } |
| 34 | +] |
| 35 | +``` |
| 36 | + |
| 37 | +```admonish warning "Elements in objects and array" |
| 38 | +In the example, we see `beginArray`, `beginElement` and `writeMember`. The functions follow a pattern: |
| 39 | +* functions without suffix, like `beginArray`, are used at the top-level |
| 40 | +* functions with `Element` suffix are used inside arrays |
| 41 | +* functions with `Member` suffix and accomanying name are used in objects |
| 42 | +
|
| 43 | +Thus, if we were writing an array inside another array, we would have used `beginArray` for the outer array and `beginArrayMember` for the inner array. These rules also apply when implementing `writeValue`. |
| 44 | +``` |
| 45 | + |
| 46 | +### Example: Writing Nested Structures |
| 47 | + |
| 48 | +Objects and arrays can be nested arbitrarily. |
| 49 | + |
| 50 | +Here is the same array of JSON objects, nested in an envelope containing an additional `status` field. |
| 51 | + |
| 52 | +Instead of manually placing `begin`/`end` pairs, we're using the convenience helpers `writeObjectElement` and `writeArrayMember`, along with `writeElement` to manage the required element markers: |
| 53 | + |
| 54 | +```nim |
| 55 | +{{#include ../examples/streamwrite1.nim:Nesting}} |
| 56 | +``` |
| 57 | + |
| 58 | +This produces a the following output - notice the more compact representation when `pretty = true` is not used: |
| 59 | +```json |
| 60 | +{"status":"ok","data":[{"id":0,"name":"item0"},{"id":1,"name":"item1"}]} |
| 61 | +``` |
| 62 | + |
| 63 | +```admonish tip |
| 64 | +Similar to `begin`, we're using the `Element` suffix in arrays! |
| 65 | +``` |
0 commit comments