I am attempting to parse some JSON using this API endpoint.
https://www.cryptocompare.com/api/data/coinlist/
I can see it's making the request fine, I then try to decode the body of the response and it comes back with loads of random numbers.
If I copy the body value from my debugger I get the below.
<[]uint8> (length: 643401, cap: 1048064)
Here is my code.
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)
I want to be able to grab everything inside the Data key from the JSON and then map that to a struct. Can anyone see what I am doing wrong?
Below is an example of what I see in my browser when I hit the endpoint.
{
"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
},
Im not sure if I understood your question correctly but here's how I would parse the response given by the 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
}
}
"I then try to decode the body of the response and it comes back with loads of random numbers."
These random numbers is the response body as a slice of bytes []byte
given by the ioutil.ReadAll()
method, which is perfect for Unmarshaling.