[英]panic: json: cannot unmarshal array into Go value of type main.Structure
I am trying to parse data from a json api. 我正在尝试从JSON API解析数据。
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type Structure struct {
stuff []interface{}
}
func main() {
url := "https://api.coinmarketcap.com/v1/ticker/?start=0&limit=100"
response, err := http.Get(url)
if err != nil {
panic(err)
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
panic(err)
}
decoded := &Structure{}
fmt.Println(url)
err = json.Unmarshal(body, decoded)
if err != nil {
panic(err)
}
fmt.Println(decoded)
}
I expected for the code to return a list of interface objects. 我希望代码返回接口对象列表。
I got an error: panic: json: cannot unmarshal array into Go value of type main.Structure
我收到一个错误:
panic: json: cannot unmarshal array into Go value of type main.Structure
The application is unmarshalling a JSON array to a struct. 该应用程序正在将JSON数组解组到结构。 Unmarshal to a slice:
解组切片:
var decoded []interface{}
err = json.Unmarshal(body, &decoded)
Consider unmarshalling to a []map[string]string or a []Tick where Tick is 考虑解组为[] map [string]字符串或[] Tick,其中Tick是
type Tick struct {
ID string
Name string
Symbol string
Rank string
... and so on
}
i had same problem. 我有同样的问题。 use this code:
使用此代码:
type coinsData struct {
Symbol string `json:"symbol"`
Price string `json:"price_usd"`
}
func main() {
resp, err := http.Get("https://api.coinmarketcap.com/v1/ticker/?limit=0")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
var c []coinsData
err = json.Unmarshal(body, &c)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%v\n", c)
}
You'll get the result: [{BTC 7986.77} {ETH 455.857} {XRP 0.580848}...] 您将得到结果:[{BTC 7986.77} {ETH 455.857} {XRP 0.580848} ...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.