gpt4 book ai didi

json - 如何在 Go 中解析数组 json?

转载 作者:IT王子 更新时间:2023-10-29 02:27:31 24 4
gpt4 key购买 nike

我有以下 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
}

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

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)

但这对我不起作用。货币为空。

它适用于数组:

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

但我想使用一个结构。

最佳答案

您的 Currency 结构只需实现 json.Unmarshaler界面。

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

关于json - 如何在 Go 中解析数组 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43013758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com