Parsing Multiple JSON Objects in Go
When dealing with JSON data, it's common to encounter situations where multiple JSON objects are returned from a server, rather than a single object enclosed in brackets. Parsing such data presents its own unique challenges.
For instance, if you have a response in the following format:
{"something":"foo"} {"something-else":"bar"}
You cannot directly use the encoding/json package to parse this data, as it expects brackets to enclose the objects.
To solve this issue, you can leverage the json.Decoder type from the encoding/json package. This type allows you to decode JSON data from a stream of bytes, making it suitable for handling multiple JSON objects.
Here's an example of how you can use json.Decoder to parse multiple JSON objects:
package main import ( "encoding/json" "fmt" "log" "strings" ) var input = ` {"foo": "bar"} {"foo": "baz"} ` type Doc struct { Foo string } func main() { dec := json.NewDecoder(strings.NewReader(input)) for { var doc Doc err := dec.Decode(&doc) if err == io.EOF { // all done break } if err != nil { log.Fatal(err) } fmt.Printf("%+v\n", doc) } }
In this example, we use a strings.NewReader to create a stream of bytes from our input string. We then create a json.Decoder to decode this stream.
Within a loop, we repeatedly call dec.Decode(&doc) to decode each JSON object into our Doc struct. The loop continues until the end of the stream, at which point err is set to io.EOF.
By utilizing json.Decoder, we can effectively parse multiple JSON objects even if they are not enclosed within brackets, allowing us to handle a wide range of JSON data formats.
The above is the detailed content of How to Parse Multiple JSON Objects in Go Without Brackets?. For more information, please follow other related articles on the PHP Chinese website!