Home >Backend Development >Golang >How to Efficiently Parse Multiple JSON Objects in Go?

How to Efficiently Parse Multiple JSON Objects in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-22 02:56:12183browse

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:

  1. Creating a json.Decoder object from the input.
  2. Iterating over the input using the Decode method of the decoder.
  3. Deserializing each JSON object into a custom struct (e.g., Doc).

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!

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