1

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

2 Answers 2

8

For everyone that is struggling to create the right structure for JSON unmarshalling, here's a cool website that convert any JSON to the right Go struct: JSON-to-Go

Sign up to request clarification or add additional context in comments.

1 Comment

Holy cow, this website is awesome. Thank you so much for sharing!
3

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.

1 Comment

Thanks! I will try it out. And yes i dont know what the reddit devs were thinking when generating that Json.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.