The function getJson
in the question decodes the JSON response body for the specified URL to the value pointed to by target
. The expression json.NewDecoder(r.Body).Decode(target)
does the following:
- create a decoder that reads from the response body
- use the decoder to unmarshal the JSON to the value pointed to by
target
.
- returns error or nil.
Here's an example use of the function. The program fetches and prints information about this answer.
func main() {
url := "https://api.stackexchange.com/2.2/answers/67655454?site=stackoverflow"
// Answers is a type the represents the JSON for a SO answer.
var response Answers
// Pass the address of the response to getJson. The getJson passes
// that address on to the JSON decoder.
err := getJson(url, &response)
// Check for errors. Adjust error handling to match the needs of your
// application.
if err != nil {
log.Fatal(err)
}
// Print the answer.
for _, item := range response.Items {
fmt.Printf("%#v", item)
}
}
type Owner struct {
Reputation int `json:"reputation"`
UserID int `json:"user_id"`
UserType string `json:"user_type"`
AcceptRate int `json:"accept_rate"`
ProfileImage string `json:"profile_image"`
DisplayName string `json:"display_name"`
Link string `json:"link"`
}
type Item struct {
Owner *Owner `json:"owner"`
IsAccepted bool `json:"is_accepted"`
Score int `json:"score"`
LastActivityDate int `json:"last_activity_date"`
LastEditDate int `json:"last_edit_date"`
CreationDate int `json:"creation_date"`
AnswerID int `json:"answer_id"`
QuestionID int `json:"question_id"`
ContentLicense string `json:"content_license"`
}
type Answers struct {
Items []*Item `json:"items"`
HasMore bool `json:"has_more"`
QuotaMax int `json:"quota_max"`
QuotaRemaining int `json:"quota_remaining"`
}
Link to complete code including code from question.