Home >Backend Development >Golang >How to Efficiently Parse Multiple JSON Objects in Go?
Parsing Multiple JSON Objects in Go
JSON parsing in Go is simplified using the encoding/json package. While it effortlessly handles arrays of JSON objects, the challenge arises when parsing JSON responses with multiple objects, such as:
{"something":"foo"} {"something-else":"bar"}
The provided code attempts to manually transform the input by replacing the }{ occurrences with },{, but this approach is ineffective.
To resolve this issue, a more robust solution using a json.Decoder is necessary. The approach involves:
Here's an example implementation:
package main import ( "encoding/json" "fmt" "io" "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) } }
This solution gracefully handles multiple JSON objects in the input, ensuring their accurate parsing and deserialization.
The above is the detailed content of How to Efficiently Parse Multiple JSON Objects in Go?. For more information, please follow other related articles on the PHP Chinese website!