以下是一个示例代码,可以获取一个API返回的JSON数据,并解析其中的一些字段:

package main

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

type Response struct {
    Status string `json:"status"`
    Message string `json:"message"`
    Data Data `json:"data"`
}

type Data struct {
    Name string `json:"name"`
    Age int `json:"age"`
}

func main() {
    url := "https://example.com/api/data"
    resp, err := http.Get(url)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer resp.Body.Close()

    var response Response
    err = json.NewDecoder(resp.Body).Decode(&response)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    fmt.Println("Status:", response.Status)
    fmt.Println("Message:", response.Message)
    fmt.Println("Name:", response.Data.Name)
    fmt.Println("Age:", response.Data.Age)
}

在上面的示例中,我们定义了两个结构体类型:ResponseDataResponse 结构体包含三个字段:StatusMessageDataData 结构体包含两个字段:NameAge

然后我们使用 http.Get 函数发送一个 GET 请求,并获取 API 返回的 JSON 数据。我们使用 json.NewDecoder 函数将 JSON 数据解码为 Response 结构体类型的变量。

最后,我们可以访问 Response 结构体的各个字段,以获取 API 返回的数据

golang 写一段http获取json 并解析

原文地址: https://www.cveoy.top/t/topic/fQMA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录