简体   繁体   English

以数组开头的Golang解组json

[英]Golang unmarshal json that starts as an array

I'm trying to unmarshal this json https://www.reddit.com/r/videos/comments/3vgdsb/recruitment_2016.json 我正在尝试解组此json https://www.reddit.com/r/videos/comments/3vgdsb/recruitment_2016.json

It starts as an array of two different objects, and I only need data on the second object. 它以两个不同对象的数组开始,我只需要第二个对象上的数据。

I want to retrieve the comments body, it doesn't give me any error when i'm trying to decode it, but it doesn't capture the data I want. 我想检索注释正文,当我尝试对其进行解码时,它不会给我任何错误,但它不会捕获我想要的数据。

This is the output I get from running this: 这是我从运行此命令得到的输出:

//Response struct when initialized: []
//Response struct decoded: [{{{[]}}} {{{[]}}}]

//// ////

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

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

The json data you are unmarshaling does not conform with your data, and if the names of the fields are not like in your struct, you should use struct tags as well. 您要解组的json数据与您的数据不一致,并且如果字段名称与struct中的字段名称不同,则也应使用struct标记。 It should be more like this: 应该更像这样:

type Response []struct {
        Kind string `json:"kind"`
        Data struct {
            Children []struct {
                Data struct {
                    Replies []struct {
                       // whatever...
                    } `json:"replies"`
                } `json:"data"`
            } `json:"children"`
        } `json:"data"`
    }
}

Of course I'd replace the inline types with real, named types, but I'm just making a point here in regards to the data hierarchy. 当然,我将用真正的命名类型替换内联类型,但是在这里我只是想说明数据层次结构。

Goddamn, that's some ugly bloated JSON BTW. 该死的,这是丑陋的,blo肿的JSON BTW。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM