jsongounmarshalling

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


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


Solution

  • The application is unmarshalling a JSON array to a struct. Unmarshal to a slice:

     var data []interface{}
     err = json.Unmarshal(body, &data)
    

    Consider unmarshalling to a slice of structs specific to the response data:

     type Tick struct {
         ID string
         Name string
         Symbol string
         Rank string
         Price_USD string
         ... and so on
    }
    
     var data []Tick
     err = json.Unmarshal(body, &data)