I’m trying to decode a Jason file. I got so I can get the data I need, but it ends up in a “ResultsType” and I can’t seem to get the specific data that I want. If I do: fmt.Println(data.Results) - it prints all the information, but now I want to example grab just the gender or the first name, how do I do that?
I tried:
fmt.Println("Print Data: ", data.Results.User.Gender)
and other ways as well, this is the one that makes most sense to me.
package main
import "fmt"
import "net/http"
import "encoding/json"
const apiURL = "http://api.randomuser.me/?nat=us"
type UserData struct {
Results []ResultsType `json:"results"`
Nationality string `json:"nationality"`
Seed string `json:"seed"`
}
type ResultsType struct {
User UserType `json:"user"`
}
type UserType struct {
Gender string
Name struct {
Title string `json:"title"`
First string `json:"first"`
Last string `json:"last"`
}
}
func main() {
res, err := http.Get(apiURL)
errorCheck(err)
defer res.Body.Close()
decoder := json.NewDecoder(res.Body)
var data UserData
err = decoder.Decode(&data)
errorCheck(err)
fmt.Println("Print Gender: ", data.User.Gender)
fmt.Println("Print Fist Name ", data.User.First.Name)
}
func errorCheck(err error) {
if err != nil {
panic(err)
}
}