panic: json: cannot unmarshal array into Go value of type main.Structure

浪尽此生 提交于 2020-01-14 14:12:33

问题


What are you trying to accomplish?

I am trying to parse data from a json api.

Paste the part of the code that shows the problem.

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)
}

What do you expect the result to be?

I expected for the code to return a list of interface objects.

What is the actual result you get?

I got an error: panic: json: cannot unmarshal array into Go value of type main.Structure


回答1:


The application is unmarshalling a JSON array to a struct. 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

 type Tick struct {
     ID string
     Name string
     Symbol string
     Rank string
     ... and so on
}



回答2:


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}...]



来源:https://stackoverflow.com/questions/47723193/panic-json-cannot-unmarshal-array-into-go-value-of-type-main-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!