0

I have the following JSON data:

[
    {
        "id": "bitcoin", 
        "name": "Bitcoin", 
        "symbol": "BTC", 
        "rank": "1", 
        "price_usd": "960.094", 
        "price_btc": "1.0", 
        "24h_volume_usd": "438149000.0", 
        "market_cap_usd": "15587054083.0", 
        "available_supply": "16234925.0", 
        "total_supply": "16234925.0", 
        "percent_change_1h": "-0.76", 
        "percent_change_24h": "-7.78", 
        "percent_change_7d": "-14.39", 
        "last_updated": "1490393946"
    }
]

And I have two struct:

type Valute struct {
    Id     string `json:"id"`
    Name   string `json:"name"`
    Symbol string `json:"symbol"`
}

type Currency struct {
    Result []Valute
}

I want to parse the array returned by this call:

resp, err := http.Get("https://api.coinmarketcap.com/v1/ticker/?limit=1")
defer resp.Body.Close()
v := Currency{}
body, err := ioutil.ReadAll(resp.Body)
json.Unmarshal(body, &v)

But it does not work for me. Currency is empty.

It works with an array:

var valutes []Valute
json.Unmarshal(body, &valutes)

But I want to use a struct.

0

2 Answers 2

3

Your Currency struct simply has to implement the json.Unmarshaler interface.

func (c *Currency) UnmarshalJSON(b []byte) error {
    return json.Unmarshal(b, &c.Result)
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can also just change to json.Unmarshal(body, &v.Result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.