Parsing Multiple JSON Objects in Go: Addressing Nested Objects
When dealing with multiple JSON objects returned from a server in the form of nested objects, the standard encoding/json package may encounter difficulties. This article delves into a solution using a json.Decoder to handle such scenarios effectively.
Consider the following example:
{"something":"foo"} {"something-else":"bar"}
Using the following code to parse this data:
correct_format := strings.Replace(string(resp_body), "}{", "},{", -1) json_output := "[" + correct_format + "]"
results in an error.
Solution Using json.Decoder
To address this issue, we utilize a json.Decoder. A json.Decoder reads and decodes JSON data stream-like, sequentially decoding individual JSON objects from the input.
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 solution:
Playground and Conclusion
You can try out this solution on the Go Playground: https://play.golang.org/p/ANx8MoMC0yq
By using a json.Decoder, we are able to parse multiple JSON objects, even when they are nested within a larger JSON structure.
The above is the detailed content of How Can I Parse Multiple JSON Objects in Go, Especially When They're Nested?. For more information, please follow other related articles on the PHP Chinese website!