Parsing multiple JSON objects in Go

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

    You can read the ndjson from the file row by row and parse it then apply the logical operations on it. In the below sample instead of reading from the file, I have used an Array of JSON string.

    import (
        "encoding/json"
        "fmt"
    )
    
    type NestedObject struct {
        D string
        E string
    }
    
    type OuterObject struct {
        A string
        B string
        C []NestedObject
    }
    
    func main() {
    
        myJsonString := []string{`{"A":"1","B":"2","C":[{"D":"100","E":"10"}]}`, `{"A":"11","B":"21","C":[{"D":"1001","E":"101"}]}`}
        for index, each := range myJsonString {
            fmt.Printf("Index value [%d] is [%v]\n", index, each)
            var obj OuterObject
            json.Unmarshal([]byte(each), &obj)
            fmt.Printf("a: %v, b: %v, c: %v", obj.A, obj.B, obj.C)
            fmt.Println()
        }
    }
    

    Output:

    Index value [0] is [{"A":"1","B":"2","C":[{"D":"100","E":"10"}]}]
    a: 1, b: 2, c: [{100 10}]
    Index value [1] is [{"A":"11","B":"21","C":[{"D":"1001","E":"101"}]}]
    a: 11, b: 21, c: [{1001 101}]
    

    Try it on golang play

提交回复
热议问题