Streaming
JsonWriter
can be used to incrementally write JSON data.
Incremental processing is ideal for large documents or when you want to avoid building the entire JSON structure in memory.
Writing
You can use JsonWriter
to write JSON objects, arrays, and values step by step, directly to a file or any output stream.
The process is similar to when you override writeValue
to provide custom serialization.
Example: Writing a JSON Array of Objects
Suppose you want to write a large array of objects to a file, one at a time:
import json_serialization, faststreams/outputs
let file = fileOutput("output.json")
var writer = JsonWriter[DefaultFlavor].init(file, pretty = true)
writer.beginArray()
for i in 0 ..< 2:
writer.beginObject()
writer.writeMember("id", i)
writer.writeMember("name", "item" & $i)
writer.endObject()
writer.endArray()
file.close()
Resulting file (output.json
):
[
{
"id": 0,
"name": "item0"
},
{
"id": 1,
"name": "item1"
}
]
Example: Writing Nested Structures
Objects and arrays can be nested arbitrarily.
Here is the same array of JSON objects, nested in an envelope containing an additional status
field.
Instead of manually placing begin
/end
pairs, we're using the convenience helpers writeObject
and writeArrayMember
, along with writeElement
to manage the required element markers:
writer.writeObject:
writer.writeMember("status", "ok")
writer.writeName("data")
writer.writeArray:
for i in 0 ..< 2:
writer.writeObject:
writer.writeMember("id", i)
writer.writeMember("name", "item" & $i)
This produces a the following output - notice the more compact representation when pretty = true
is not used:
{"status":"ok","data":[{"id":0,"name":"item0"},{"id":1,"name":"item1"}]}