如何解析cryptocompare API生成的JSON?

时间:2017-12-12 16:18:58

标签: json go

我正在尝试使用此API端点解析一些JSON。

https://www.cryptocompare.com/api/data/coinlist/

我可以看到它使请求变得很好,然后我尝试解码响应的主体,并且它会随着大量的随机数字返回。

如果我从调试器中复制正文值,我会得到以下内容。

  

的百分比抑制率] UINT8> (长度:643401,上限:1048064)

这是我的代码。

url := fmt.Sprintf("https://www.cryptocompare.com/api/data/coinlist/")

    fmt.Println("Requesting data from " + url)

    req, err := http.NewRequest("GET", url, nil)

    if err != nil {
        log.Fatal("NewRequest: ", err)
        return
    }

    client := &http.Client{}

    resp, err := client.Do(req)

    if err != nil {
        log.Fatal("Do: ", err)
        return
    }

    body, readErr := ioutil.ReadAll(resp.Body)

我希望能够从JSON中获取Data键中的所有内容,然后将其映射到结构。谁能看到我做错了什么?

以下是我点击端点时在浏览器中看到的示例。

 {
"Response": "Success",
"Message": "Coin list succesfully returned! This api is moving to https://min-api.cryptocompare.com/data/all/coinlist, please change the path.",
"BaseImageUrl": "https://www.cryptocompare.com",
"BaseLinkUrl": "https://www.cryptocompare.com",
"DefaultWatchlist": {
"CoinIs": "1182,7605,5038,24854,3807,3808,202330,5324,5031,20131",
"Sponsored": ""
},
"Data": {
"42": {
"Id": "4321",
"Url": "/coins/42/overview",
"ImageUrl": "/media/12318415/42.png",
"Name": "42",
"Symbol": "42",
"CoinName": "42 Coin",
"FullName": "42 Coin (42)",
"Algorithm": "Scrypt",
"ProofType": "PoW/PoS",
"FullyPremined": "0",
"TotalCoinSupply": "42",
"PreMinedValue": "N/A",
"TotalCoinsFreeFloat": "N/A",
"SortOrder": "34",
"Sponsored": false
},

1 个答案:

答案 0 :(得分:1)

我不确定我是否正确理解了您的问题,但这是我将如何解析API给出的响应:

package main

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

type Data struct {
    Id        string
    CoinName  string
    Algorithm string
    // You can add more properties if you need them
}

type Response struct {
    Response         string
    Message          string
    BaseImageUrl     string
    BaseLinkUrl      string
    DefaultWatchlist map[string]string
    // If you're interested in the Data only all of the above properties can be excluded
    Data             map[string]Data
}

func main() {
    url := "https://min-api.cryptocompare.com/data/all/coinlist"
    resp := Response{}

    // Getting the data using http
    r, err := http.Get(url)
    if err != nil {
        log.Fatal(err.Error())
    }

    // Reading the response body using ioutil
    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        log.Fatal(err.Error())
    }
    defer r.Body.Close()

    if r.StatusCode == http.StatusOK {
        // Unmarshaling the json bytes into Response struct
        json.Unmarshal(body, &resp)

        fmt.Println(resp.Data) // Printing parsed struct
    }
}
  

“然后我尝试对响应的主体进行解码,并返回大量随机数。”

这些随机数[]byte方法给出的字节ioutil.ReadAll()切片的响应主体,非常适合 Unmarshaling