Home >Backend Development >Golang >How to Fix 'json: cannot unmarshal array into Go value of type main.Structure'?
When trying to parse JSON data from an API, users may encounter the error: "panic: json: cannot unmarshal array into Go value of type main.Structure."
type Structure struct { stuff []interface{} } ... // more code decoded := &Structure{} err = json.Unmarshal(body, decoded)
The root of the issue is the attempt to unmarshal a JSON array into a Go struct.
Option 1: Unmarshal to a slice
Instead of using a struct, unmarshal the JSON array to a slice of interface{}:
var data []interface{} err = json.Unmarshal(body, &data)
Option 2: Unmarshal to a slice of structs
If the JSON data has a specific structure, consider creating a slice of structs that match the response data:
type Tick struct {...} var data []Tick err = json.Unmarshal(body, &data)
The above is the detailed content of How to Fix 'json: cannot unmarshal array into Go value of type main.Structure'?. For more information, please follow other related articles on the PHP Chinese website!