Parsing multiple JSON objects in Go

前端 未结 4 1598
-上瘾入骨i
-上瘾入骨i 2021-01-21 01:55

Objects like the below can be parsed quite easily using the encoding/json package.

[ 
    {\"something\":\"foo\"},
    {\"something-else\":\"bar\"}
         


        
4条回答
  •  长发绾君心
    2021-01-21 02:38

    Assuming your input is really a series of valid JSON documents, use a json.Decoder to decode them:

    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)
        }
    }
    

    Playground: https://play.golang.org/p/ANx8MoMC0yq

    If your input really is what you've shown in the question, that's not JSON and you have to write your own parser.

提交回复
热议问题