PLZ*_*ELP 3 json go unmarshalling
我试图解析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)
}
Run Code Online (Sandbox Code Playgroud)
我希望代码返回一个接口对象列表.
我收到一个错误: panic: json: cannot unmarshal array into Go value of type main.Structure
小智 11
我有同样的问题。使用此代码:
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)
}
Run Code Online (Sandbox Code Playgroud)
你会得到结果:[{BTC 7986.77} {ETH 455.857} {XRP 0.580848}...]
该应用程序将JSON数组解组为结构.解组切片:
var decoded []interface{}
err = json.Unmarshal(body, &decoded)
Run Code Online (Sandbox Code Playgroud)
考虑解组到[] map [string]字符串或[] Tick中的Tick
type Tick struct {
ID string
Name string
Symbol string
Rank string
... and so on
}
Run Code Online (Sandbox Code Playgroud)