Home >Backend Development >Golang >Why Does JSON Unmarshaling an Array into a Go Struct Cause a Panic?
Panic: JSON Unmarshal Array into Go Struct
When attempting to parse data from a JSON API, you encountered the error: "panic: json: cannot unmarshal array into Go value of type main.Structure." The issue arises when unmarshalling a JSON array into a Go struct.
Your Code:
type Structure struct { stuff []interface{} } func main() { // ... decoded := &Structure{} err = json.Unmarshal(body, decoded) }
Expected Result:
You expected the code to return a list of interface objects.
Actual Result:
Instead, you received an error indicating that the JSON array could not be unmarshalled into the Structure Go value.
Solution:
To resolve this issue, consider two approaches:
Unmarshal to a Slice:
Replace the line:
decoded := &Structure{}
with:
var data []interface{}
This will unmarshal the JSON array to a slice of interfaces.
Unmarshal to a Slice of Structs:
Create specific structs for the response data structure. For example:
type Tick struct { ID string Name string Symbol string Rank string Price_USD string }
Then, unmarshal to a slice of these structs:
var data []Tick err = json.Unmarshal(body, &data)
The above is the detailed content of Why Does JSON Unmarshaling an Array into a Go Struct Cause a Panic?. For more information, please follow other related articles on the PHP Chinese website!