英文:
How to get data from external api using GO?
问题
我有外部数据,需要从中获取数据,并从 API 端点获取结果。
{
"data": [
{
"id": 30002005,
"name": "test",
"info": "{\"Version\":\"7.0.484\",\"CompanyName\":\"test\"}"
},
......
]
}
我需要获取这些数据并重新格式化到我的情况中(将数据放入结构体中,然后进行其他操作)。
Go 代码如下:
type OldData struct {
Id string `json:"id"`
Name string `json:"name"`
}
func Index() {
url := "https://exmaple.com/api/posts"
var bearer = "Bearer XXXXXX"
req, err := http.NewRequest("GET", url, nil)
req.Header.Add("Authorization", bearer)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println(err)
}
var record OldData
json.Unmarshal(body, &record)
fmt.Println(record)
}
fmt.Println(record)
的结果是 {}
。
更新
我为 info
创建了一个结构体:
type OldData struct {
Id string `json:"id"`
Name string `json:"name"`
Info string `json:"info"`
}
type Info struct {
Version string `json:"Version"`
CompanyName string `json:"CompanyName"`
}
英文:
I have external data I need to get data from it and this result from an API endpoint
{
"data": [
{
"id": 30002005,
"name": "test",
"info": "{"Version":"7.0.484","CompanyName":"test"}",
},
......
]
}
I need to get this data and reformat it to my case (put the data into struct then do whatever i need).
The go code:
type OldData struct {
Id string `json:"id"`
Name string `json:"name"`
}
func Index() {
url := "https://exmaple.com/api/posts"
var bearer = "Bearer XXXXXX"
req, err := http.NewRequest("GET", url, nil)
req.Header.Add("Authorization", bearer)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Println(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println(err)
}
var record OldData
json.Unmarshal(body, &record)
fmt.Println(record)
}
The result of fmt.Println(record)
is { }
Update
I create thrid for info :
type OldData struct {
Id string `json:"id"`
Name string `json:"name"`
Info string `json:"info"`
}
type Info struct {
Version string `json:"Version"`
CompanyName string `json:"CompanyName"`
}
答案1
得分: 3
在JSON中有一个名为data
的数组。你正在尝试将其解组为一个单独的结构体。试着定义一个结构体,其中包含一个名为data
的切片字段:
type OldData struct {
Id string `json:"id"`
Name string `json:"name"`
}
type OldDataItems struct {
Data []OldData `json:"data"`
}
现在尝试将其解组为OldDataItems
的实例。
英文:
In the JSON there is an array, named data
. You're trying to unmarshal it to a single struct. Try to define a struct which has a data field which is a slice:
type OldData struct {
Id string `json:"id"`
Name string `json:"name"`
}
type OldDataItems struct {
Data []OldData `json:"data"`
}
Now try to unmarshal into an instance of OldDataItems
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论