Streaming an array of objects
This recipe is useful if you have a generator (a goroutine, a database cursor, etc.) that produces data elements, and you want to stream these as a JSON array instead of storing everything before marshaling it.
How to do it...
- Create a generator. This can be
- a goroutine that sends data elements through a channel,
- a cursor-like object containing a
Next()
method, - or some other data generator.
- Create an instance of
json.Encoder
withio.Writer
representing the target. The target can be a file, standard output, a buffer, a network connection, and so on. - Write the array beginning delimiter for the array, that is,
[
. - Encode each data element, preceded by a comma if necessary.
- Write the array closing delimiter, that is,
]
.
The following example assumes there is a generator goroutine writing Data
instances to the input
channel. The generator closes the channel when there are no more Data
instances. Here, we assume Data
is JSON...