Home >Backend Development >Golang >Why Does JSON Unmarshal Fail When Mapping Arrays to Go Structs?
Unable to Unmarshal JSON Array into Go Structure
In an attempt to parse data from a JSON API, a programmer encountered the error: "panic: json: cannot unmarshal array into Go value of type main.Structure."
Problem Excerpt:
type Structure struct { stuff []interface{} } ... decoded := &Structure{} err = json.Unmarshal(body, decoded)
Expected Result:
A list of interface objects.
Actual Result:
panic: json: cannot unmarshal array into Go value of type main.Structure
Solution:
The issue arises when trying to unmarshal a JSON array into a Go struct. To resolve this, one can either:
var data []interface{} err = json.Unmarshal(body, &data)
type Tick struct { ID string Name string ... and so on } var data []Tick err = json.Unmarshal(body, &data)
By customizing the struct type to match the structure of the response data, the unmarshaling process will successfully parse the JSON array.
The above is the detailed content of Why Does JSON Unmarshal Fail When Mapping Arrays to Go Structs?. For more information, please follow other related articles on the PHP Chinese website!