Home > Backend Development > Golang > How Can I Efficiently Parse Multiple Consecutive JSON Objects in Go?

How Can I Efficiently Parse Multiple Consecutive JSON Objects in Go?

DDD
Release: 2024-12-23 05:08:14
Original
443 people have browsed it

How Can I Efficiently Parse Multiple Consecutive JSON Objects in Go?

Parsing Multiple JSON Objects in Go

When encountering multiple JSON objects, such as those returned from servers in the format:

{"something":"foo"}
{"something-else":"bar"}
Copy after login

parsing can prove challenging. The following code snippet demonstrates difficulties encountered when using strings.Replace:

correct_format := strings.Replace(string(resp_body), "}{", "},{", -1)
json_output := "[" + correct_format + "]"
Copy after login

An alternative solution lies in utilizing a json.Decoder for effective decoding:

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

This approach ensures successful parsing of multiple JSON objects, even in scenarios such as Common Crawl data.

The above is the detailed content of How Can I Efficiently Parse Multiple Consecutive 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template