Parsing multiple JSON objects in Go

前端 未结 4 1569
-上瘾入骨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:43

    Another option would be to parse each incoming line, line by line, and then add each one to a collection in code (ie a slice) Go provides a line scanner for this.

    yourCollection := []yourObject{}
    scanner := bufio.NewScanner(YOUR_SOURCE)
    for scanner.Scan() {
        obj, err := PARSE_JSON_INTO_yourObject(scanner.Text())
        if err != nil {
           // something
        }
        yourCollection = append(yourCollection, obj)
    }
    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "reading standard input:", err)
    }
    

提交回复
热议问题