简体   繁体   中英

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

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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