Skip to content

Commit 14e02ce

Browse files
committed
Add array streaming helpers
An implementation of #112 that introduces a rich set of helpers for creating arrays using a backwards-compatible approach that maintains the current semantic model of the array/object writer being responsible for introducing plumbing. Since the "outer" level drives the plumbing, we add writers for every combination of value and context: `beginArray`, `beginArrayElement` and `beginArrayMember` for creating an array in top-level, array and object respectively and the same for other values. In this model, `writeValue` itself performs no begin/end tracking - instead, it is up to the entity that creates the array/object to do so (`writeRecordValue`, `stepwiseArrayCreation` and so on). 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.beginObjectElement() writer.writeMember("id", i) writer.writeMember("name", "item" & t.childName[i]) writer.endObjectElement() writer.endArray() ``` The writing API is quite regular but requires calling special functions depending on the context which is easy to forget - calling the wrong variation results in invalid JSON! The backwards-compatiblity issue can be seen in a new test case based on a real-world example for writing byte arrays as hex strings. Further examples are available in the documentation.
1 parent 565a797 commit 14e02ce

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

json_serialization/writer.nim

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -453,7 +453,7 @@ proc writeValue*[V: not void](w: var JsonWriter, value: V) {.raises: [IOError].}
453453
discard
454454

455455
elif value is ref:
456-
if value == nil:
456+
if value.isNil:
457457
append "null"
458458
else:
459459
writeValue(w, value[])

0 commit comments

Comments
 (0)