Golang解组以数组开头的json

Mar*_*iar 1 json decode go

我正在尝试解组这个 json https://www.reddit.com/r/videos/comments/3vgdsb/recruitment_2016.json

它从两个不同对象的数组开始,我只需要第二个对象的数据。

我想检索评论正文,当我尝试对其进行解码时它没有给我任何错误,但它没有捕获我想要的数据。

这是我从运行中得到的输出:

//Response struct when initialized: []
//Response struct decoded: [{{{[]}}} {{{[]}}}]
Run Code Online (Sandbox Code Playgroud)

////

type Response []struct {
    Parent struct {
        Data struct {
            Children []struct {
                Com Comment
            }
        }
    }
}

type Comment struct {
    Name string `json:"body"`
}

func init() {
    http.HandleFunc("/api/getcomments", getComments)
}

func getComments(w http.ResponseWriter, r *http.Request) {

    url := "https://www.reddit.com/r/videos/comments/3vgdsb/recruitment_2016.json"
    c := appengine.NewContext(r)
    client := urlfetch.Client(c)
    resp, err := client.Get(url)
    if err != nil { fmt.Fprint(w, "Error client.Get(): ", err) }

    re := new(Response)
    fmt.Fprint(w, "Response struct: ", re, "\n")

    errTwo := json.NewDecoder(resp.Body).Decode(&re)
    if errTwo != nil {  fmt.Fprint(w, "Error decoding: ", errTwo, "\n") }

    fmt.Fprint(w, "Response struct: ", re)
}
Run Code Online (Sandbox Code Playgroud)

小智 7

对于正在努力为 JSON 解组创建正确结构的每个人,这里有一个很酷的网站,可以将任何 JSON 转换为正确的 Go 结构:JSON-to-Go