我对 Go 还很陌生,并且仍在为一些概念而苦苦挣扎。我已经到处搜索以找到解决方案,但我尝试的一切似乎都不起作用;我想我搞砸了我的结构。我正在使用 Alpha Vantage API 并尝试将响应解组为一个结构,但它返回一个空结构。这是我的代码:package mainimport ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os")type stockData struct { GlobalQuote string tickerData tickerData}type tickerData struct { Symbol string `json:"01. symbol"` Open string `json:"02. open"` High string `json:"03. high"` Low string `json:"04. low"` Price string `json:"05. price"` Volume string `json:"06. volume"` LatestTradingDay string `json:"07. latest trading day"` PreviousClose string `json:"08. previous close"` Change string `json:"09. change"` ChangePercent string `json:"10. change percent"`}func main() { // Store the PATH environment variable in a variable AVkey, _ := os.LookupEnv("AVkey") // This is a separate function that is not necessary for this question url := (buildQueryURL("GOOG", AVkey)) resp, err := http.Get(url) if err != nil { fmt.Println(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) } bodyString := fmt.Sprintf("%s", body) var data stockData if err := json.Unmarshal([]byte(bodyString), &data); err != nil { panic(err) } fmt.Println(data)}但它返回以下内容:{ { }}这是json正文:bodyString := `{ "Global Quote": { "01. symbol": "GOOG", "02. open": "1138.0000", "03. high": "1194.6600", "04. low": "1130.9400", "05. price": "1186.9200", "06. volume": "2644898", "07. latest trading day": "2020-04-06", "08. previous close": "1097.8800", "09. change": "89.0400", "10. change percent": "8.1102%" }}`我哪里错了?我认为这与自定义结构有关,但我无法在 Google 搜索的帮助下修复它。
1 回答

慕哥6287543
TA贡献1831条经验 获得超10个赞
修改 stockData 类型以匹配 JSON 数据的结构:
type stockData struct {
GlobalQuote tickerData `json:"Global Quote"`
}
- 1 回答
- 0 关注
- 115 浏览
添加回答
举报
0/150
提交
取消