Home >Backend Development >Golang >How to Parse Multiple Unwrapped JSON Objects in Go?
Parsing Multiple Unwrapped JSON Objects in Go
In Go, the encoding/json package efficiently parses JSON objects enclosed within square brackets ([]). However, encountering multiple unwrapped JSON objects (e.g., {key:value}{key:value}) presents a parsing challenge.
To decode such multiple unwrapped JSON objects, we can employ a json.Decoder that iteratively reads and decodes each individual object. Here's an example:
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) } }
In this example:
Playground: https://play.golang.org/p/ANx8MoMC0yq
The above is the detailed content of How to Parse Multiple Unwrapped JSON Objects in Go?. For more information, please follow other related articles on the PHP Chinese website!