dqpdb82600 2018-05-29 09:49
浏览 54
已采纳

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

I am new to Go lang have created a REST client that consumes the alphavantage API

The JSON structure which comes up after I make a GET request looks as below. I only need the Time Series key data so that I do my own calculations. How do I get the data from the Time Series and save it so that I do my own manipulations of the data?

JSON

{
    "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"
        }
    }
}

code for REST Client

package main

import (
    "net/http"
    "fmt"
    "io/ioutil"
    //encode and decode JSON streams
    "encoding/json"
)



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
    }
    fmt.Println(string(contents))
}
  • 写回答

1条回答 默认 最新

  • dsi36131 2018-05-29 10:27
    关注

    Using an interface as suggested is a good idea, but in this case, since you know the structure of the response defining using an explicit type suffices and should be easier to work with:

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题