Parsing Multiple JSON Objects in Go
When encountering multiple JSON objects, such as those returned from servers in the format:
{"something":"foo"} {"something-else":"bar"}
parsing can prove challenging. The following code snippet demonstrates difficulties encountered when using strings.Replace:
correct_format := strings.Replace(string(resp_body), "}{", "},{", -1) json_output := "[" + correct_format + "]"
An alternative solution lies in utilizing a json.Decoder for effective decoding:
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 approach ensures successful parsing of multiple JSON objects, even in scenarios such as Common Crawl data.
The above is the detailed content of How Can I Efficiently Parse Multiple Consecutive JSON Objects in Go?. For more information, please follow other related articles on the PHP Chinese website!