mirror of
https://github.com/status-im/nim-json-serialization.git
synced 2026-08-31 02:41:06 +00:00
An implementation of https://github.com/status-im/nim-json-serialization/issues/112 that introduces `beginArray`/`endArray` for the streaming creation of arrays. In order to accomodate the need for intra-element plumbing, we add `begin`/`end` marker calls to the `writeValue` implementation which helps the writer keep track of each value being written and therefore allows it to inject the correct delimiters and indents. Here's an example of writing a `writeValue` overload that writes an array nested in an object: ```nim proc writeValue(w: var JsonWriter, t: MyType) = w.beginArray() for i in 0 ..< t.children: writer.beginObject() writer.writeMember("id", i) writer.writeMember("name", "item" & t.childName[i]) writer.endObject() writer.endArray() ``` Similar to the existing `beginRecord`/`endRecord` fields we add `beginArray` and `endArray` - we also take the opportunity to name `beginObject` according to its json-spec-derived name. The old name remains available. This change introduces a backwards-compatibility break for custom writers that try to access the stream directly: they now have to delimit their value writing with `w.streamElement(s): s.write ...` where `s` is the stream variable. The block template enforces begin/end markers on behalf of the writer. Further examples are available in the documentation. With this change, we also deprecate workarounds like `fieldWritten` and `endRecordField` since a regular replacement exists in the form of consistent begin/end pairs. * doc fixes * make beginElement/endElement private Should not be called directly as `writeValue` / `streamElement` take care of it.
19 lines
341 B
Nim
19 lines
341 B
Nim
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()
|