DBA108642
DBA108642

Reputation: 2112

Golang unmarshal a nested json into a struct

I am fairly new to Go and am still struggling with some concepts. I have googled all over to find a solution to this, but everything I try seems to not work; I think I'm screwing up my structs. I'm hitting the Alpha Vantage API and trying to unmarshal the response into a struct, but it returns an empty struct. here is my code:

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)
}

but it returns the following:

{ {         }}

And here is the json body:

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%"
    }
}`

Where am I going wrong? I think it's something to do with the custom structs, but I haven't been able to fix it with help from Google searches.

Upvotes: 0

Views: 171

Answers (1)

thwd
thwd

Reputation: 26

Modify the stockData type to match the structure of the JSON data:

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

Try running it on the playground

Upvotes: 1

Related Questions