I just recently started working with apis and http requests and I'm trying to build an application that uses the Reddit API to pull posts on a specific subreddit.
This is the the page with json and search parameters that I'm practicing on: https://www.reddit.com/r/hiphopheads.json?limit=1
Looking at the standard library of the JSON module for Golang, I still don't understand how to use json.Unmarshal for this complex JSON. From what I gather, I have to define a struct that resembles the JSON structure to actually hold the data
I posted the link into this website to get a feel for what the JSON is actually strucutred like: https://jsonformatter.curiousconcept.com/
Right now the main thing I'm after is the title which is under Data->Children->Data->Title. If I want to unmarshal the JSON into an object, do I define a nested struct object? Or is there a simpler way to do this so that I don't have to figure out all the attributes of the JSON and define them myself??
Any help that can get me on the right track is greatly appreciated. Thanks!
You don't have to define fields you don't need in your struct. Unmarshal will only decode the values that are present in your struct. But with nested JSONs you unfortunately have to define all the parent fields also (unlike in xml package in which you can define paths in tags). So your struct could look like this:
type Foo struct {
Data struct {
Children []struct {
Data struct {
Title string
}
}
}
}
See here for a working example: https://play.golang.org/p/UeUYfWBONL