json{
"jsonrpc": "2.0",
"id": "123123123",
"result": {
"list": [{
"portfolioName": "基金多只",
"portfolioID": "TG20240221000005",
"portfolioType": 4,
"subAccountID": "99688015101",
"followerStatus": 3
},
{
"portfolioName": "基金+债券组合amy",
"portfolioID": "TG20240223000002",
"portfolioType": 4,
"subAccountID": "99688015102",
"followerStatus": 3
}
],
"count": 2
}
}
我现在需要一次性把里面的数据全部拿出来然后存起来,这样就避免重复的调用http,请问代码该怎么写
要一次性提取这个接口返回的数据并存储起来,你可以按照以下步骤操作:
net/http包发起HTTP请求到指定的接口。encoding/json包解析接口返回的JSON数据到之前定义的结构体中。以下是一个简化的示例,展示了如何完成这个过程:
gopackage main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
// PortfolioItem 定义了list中每个项目的结构
type PortfolioItem struct {
PortfolioName string `json:"portfolioName"`
PortfolioID string `json:"portfolioID"`
PortfolioType int `json:"portfolioType"`
SubAccountID string `json:"subAccountID"`
FollowerStatus int `json:"followerStatus"`
}
// Response 定义了整个JSON响应的结构
type Response struct {
Result struct {
List []PortfolioItem `json:"list"`
Count int `json:"count"`
} `json:"result"`
}
func main() {
// 替换为实际的URL
url := "http://example.com/api/path"
resp, err := http.Get(url)
if err != nil {
fmt.Printf("Error fetching data: %v\n", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Error reading response body: %v\n", err)
return
}
var response Response
if err := json.Unmarshal(body, &response); err != nil {
fmt.Printf("Error parsing JSON: %v\n", err)
return
}
// 此时,response.Result.List 包含了所有你需要的数据
// 以下代码仅为展示如何访问这些数据
for _, item := range response.Result.List {
fmt.Printf("%+v\n", item)
}
// 在这里,你可以将response.Result.List存储到数据库或其他存储系统中
}
在这个示例中,我们首先定义了PortfolioItem和Response两个结构体来映射JSON数据。然后,我们使用http.Get函数从指定的URL获取数据。获取到的响应体被读取并解析为Response结构体的实例。最后,我们遍历response.Result.List来展示如何访问解析后的数据。
请确保替换url变量的值为你实际的接口URL。此外,根据你的实际情况,你可能需要将解析后的数据存储到数据库或其他存储系统中,这一步在示例代码中以注释的形式提到。
本文作者:JIeJaitt
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!