Parsing an array of objects
If you have a JSON data source providing an array of objects, you can parse these elements and process them using json.Decoder
.
How to do it...
- Create
json.Decoder
reading from the input stream. - Parse the array beginning delimiter (
[
) usingjson.Decoder.Token()
. - Decode each element of the array until decoding fails.
- When decoding fails, you have to determine whether the stream ended, or whether there is really an error. To check for that, read the next token using
json.Decoder.Token()
. If the next token is read successfully and if it is an array end delimiter,]
, then the stream parsing ended successfully. Otherwise, there is an error in the input data.
The following example assumes that json.Decoder
is already constructed to read from an input stream. The output is stored in a slice. Alternatively, the output can be processed as elements are parsed, or each element can be sent to a processing goroutine through a channel...