在Go中使用外部API后,使用REST客户端保存数据

时间:2018-05-29 09:49:24

标签: go serialization deserialization marshalling unmarshalling

我是{ lang的新手,已经创建了一个使用alphavantage API的REST客户端

我发出Go请求后出现的JSON结构如下所示。我只需要GET密钥数据,以便我自己进行计算。如何从Time Series获取数据并保存,以便我自己操作数据?

JSON

Time Series
代码
{
    "Meta Data": {
        "1. Information": "Intraday (1min) prices and volumes",
        "2. Symbol": "MSFT",
        "3. Last Refreshed": "2018-05-25 16:00:00",
        "4. Interval": "1min",
        "5. Output Size": "Compact",
        "6. Time Zone": "US/Eastern"
    },
    "Time Series (1min)": {
        "2018-05-25 16:00:00": {
            "1. open": "98.2700",
            "2. high": "98.4400",
            "3. low": "98.2650",
            "4. close": "98.3600",
            "5. volume": "2466507"
        }
    }
}

1 个答案:

答案 0 :(得分:1)

使用建议的界面是一个好主意,但在这种情况下,因为您知道使用显式类型定义的响应结构,并且应该更容易使用:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

type values map[string]string
type TimeSeries struct {
    Item map[string]values `json:"Time Series (1min)"`
}

func main() {
    response, err := http.Get("https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=demo")

    if err != nil {
        fmt.Println(err)
        return
    }
    defer response.Body.Close()
    contents, err := ioutil.ReadAll(response.Body)
    if err != nil {
        fmt.Println(err)
        return
    }
    var ts TimeSeries
    err = json.Unmarshal(contents, &ts)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%#v", ts)
}