How to parse array json in Go?

huangapple go评论66阅读模式
英文:

How to parse array json in Go?

问题

我有以下的JSON数据:

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

我有两个结构体:

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

type Currency struct {
    Result []Valute `json:""`
}

我想解析这个调用返回的数组:

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)

但是对我来说不起作用。Currency 是空的。

它可以用一个数组来工作:

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

但是我想使用一个结构体。

英文:

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.

答案1

得分: 3

你的Currency结构体只需要实现json.Unmarshaler接口。

func (c *Currency) UnmarshalJSON(b []byte) error {
    return json.Unmarshal(b, &c.Result)
}
英文:

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

func (c *Currency) UnmarshalJSON(b []byte) error {
	return json.Unmarshal(b, &c.Result)
}

答案2

得分: 2

你也可以直接改成 json.Unmarshal(body, &v.Result)

英文:

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

huangapple
  • 本文由 发表于 2017年3月25日 15:30:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/43013758.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定