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

How to Parse Multiple Unwrapped JSON Objects in Go?

Patricia Arquette
Release: 2024-12-25 18:23:13
Original
906 people have browsed it

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)
    }
}
Copy after login

In this example:

  • We create a json.Decoder from the input string.
  • Using a loop, we repeatedly attempt to decode individual objects from the input using dec.Decode().
  • If the decoding encounters end-of-file (io.EOF), we exit the loop as there are no more objects to decode.
  • For each successfully decoded object, we marshal it into a Doc struct and print it.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template