Home >Backend Development >Golang >How Can I Parse Multiple JSON Objects in Go, Especially When They're Nested?

How Can I Parse Multiple JSON Objects in Go, Especially When They're Nested?

DDD
DDDOriginal
2024-12-26 09:03:09791browse

How Can I Parse Multiple JSON Objects in Go, Especially When They're Nested?

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:

  • A json.Decoder is initialized to read from a string containing the JSON data.
  • A loop iterates over the stream, decoding each JSON object into a Doc struct.
  • Decoding continues until io.EOF (end of file) is encountered, indicating the end of the stream.
  • Each successfully decoded object is printed.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn