Golang将嵌套的json分解为一个结构



我是Go的新手,仍在为一些概念而挣扎。我在谷歌上到处搜索,想找到解决方案,但我尝试的一切似乎都不起作用;我想我把我的结构搞砸了。我正在访问AlphaVantage API,并试图将响应解组为一个结构,但它返回一个空结构。这是我的代码:

package main
import (
"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%"
}
}`

我哪里错了?我认为这与自定义结构有关,但我还没能在谷歌搜索的帮助下解决它。

修改stockData类型以匹配JSON数据的结构:

type stockData struct {
GlobalQuote tickerData `json:"Global Quote"`
}

试着在操场上运行

相关内容

最新更新