How to read from array json response in Go

huangapple go评论78阅读模式
英文:

How to read from array json response in Go

问题

我有一个API请求,返回一个包含refresh_token的数组,大致如下所示:

[
  {
    "refresh_token" : "C61551CEA183EDB767AA506926F423B339D78E2E2537B4AC7F8FEC0C29988819"
  }
]

我需要访问这个refresh_token的值,并将其用于查询另一个API。

为了做到这一点,我尝试首先使用'ReadAll'读取响应体,然后通过调用'refreshToken'来访问其中的键。

然而,这并没有起作用。有人知道如何解决这个问题吗?因为我无法弄清楚。

以下是我的代码:

func Refresh(w http.ResponseWriter, r *http.Request) {

	client := &http.Client{}

	// q := url.Values{}

	fetchUrl := "https://greatapiurl.com"

	req, err := http.NewRequest("GET", fetchUrl, nil)

	if err != nil {
		fmt.Println("Errorrrrrrrrr")
		os.Exit(1)
	}

	req.Header.Add("apikey", os.Getenv("ENV"))
	req.Header.Add("Authorization", "Bearer "+os.Getenv("ENV"))

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Ahhhhhhhhhhhhh")
		os.Exit(1)
	}

	respBody, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(respBody["refresh_token"])

	w.WriteHeader(resp.StatusCode)
	w.Write(respBody)
}

请注意,我只翻译了你提供的代码部分,其他部分不包括在内。

英文:

I have an API request that returns a refresh_token inside array, which looks something like this:

[
  {
    "refresh_token" : "C61551CEA183EDB767AA506926F423B339D78E2E2537B4AC7F8FEC0C29988819"
  }
]

I need to access this refresh_token's value, and use it to query another API.

To do this, I'm attempting to first 'ReadAll' the response body, and then access the key inside of it by calling 'refreshToken'.

However, it's not working. Does anyone know how to resolve this as I can't figure it out?

Here's my code:

func Refresh(w http.ResponseWriter, r *http.Request) {

	client := &http.Client{}

	// q := url.Values{}

	fetchUrl := "https://greatapiurl.com"

	req, err := http.NewRequest("GET", fetchUrl, nil)

	if err != nil {
		fmt.Println("Errorrrrrrrrr")
		os.Exit(1)
	}

	req.Header.Add("apikey", os.Getenv("ENV"))
	req.Header.Add("Authorization", "Bearer "+os.Getenv("ENV"))

	resp, err := client.Do(req)

	if err != nil {
		fmt.Println("Ahhhhhhhhhhhhh")
		os.Exit(1)
	}

	respBody, _ := ioutil.ReadAll(resp.Body)

	fmt.Println(respBody["refresh_token"])

	w.WriteHeader(resp.StatusCode)
	w.Write(respBody)
}

答案1

得分: 2

如果您不需要将其作为自定义类型,您可以将其转换为[]map[string]string

respBody, _ := ioutil.ReadAll(resp.Body)
var body []map[string]string
json.Unmarshal(respBody, &body)
fmt.Println(body[0]["refresh_token"])
英文:

If you do not need it as custom type you can cast it as []map[string]string

respBody, _ := ioutil.ReadAll(resp.Body)
var body []map[string]string
json.Unmarshal(respBody, &body)
fmt.Println(body[0]["refresh_token"])

huangapple
  • 本文由 发表于 2021年10月5日 23:33:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/69453367.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定