Golang将嵌套的json解组到结构中

时间:2020-04-06 23:28:31

标签: json go struct

我对Go语言还很陌生,但仍在努力解决一些概念。我到处搜寻Google来寻找解决方案,但是我尝试的所有事情似乎都行不通。我想我正在搞砸我的结构。我正在使用Alpha Vantage 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%"
    }
}`

我要去哪里错了?我认为这与自定义结构有关,但是在Google搜索的帮助下,我无法对其进行修复。

1 个答案:

答案 0 :(得分:1)

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

drwxrwxr-x 12 root www-data  4096 Apr  5 19:36 StudBud1
-rw-rw-r--  1 root www-data 204800 Apr  5 19:36 db.sqlite3

Try running it on the playground

相关问题