-1

I'm trying get body from response which is json and print this json or be able to put him to array. I find this post on stack: How to get JSON response from http.Get . There is code:

var myClient = &http.Client{Timeout: 10 * time.Second}

func getJson(url string, target interface{}) error {
    r, err := myClient.Get(url)
    if err != nil {
        return err
    }
    defer r.Body.Close()

    return json.NewDecoder(r.Body).Decode(target)
}

but I don't undestand why there is "Decode(target)" and "target interface{}". What does it do? Why when I try just print json.NewDecoder(r.Body) there is nothing meaningful.

2 Answers2

1

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.

-1

Here is an example:

package main

import (
   "encoding/json"
   "net/http"
)

func main() {
   r, e := http.Get("https://github.com/manifest.json")
   if e != nil {
      panic(e)
   }
   defer r.Body.Close()
   var s struct { Name string }
   json.NewDecoder(r.Body).Decode(&s)
   println(s.Name == "GitHub")
}

https://golang.org/pkg/encoding/json#Decoder.Decode

Zombo
  • 1
  • 62
  • 391
  • 407